diff --git a/examples/contrib/3_jugs_regular.cs b/examples/contrib/3_jugs_regular.cs index 7bd612b44a..05d3c332b2 100644 --- a/examples/contrib/3_jugs_regular.cs +++ b/examples/contrib/3_jugs_regular.cs @@ -42,8 +42,7 @@ public class ThreeJugsRegular { * F : accepting states * */ - static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[, ] d, - int q0, int[] F) { + static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[,] d, int q0, int[] F) { Debug.Assert(Q > 0, "regular: 'Q' must be greater than zero"); Debug.Assert(S > 0, "regular: 'S' must be greater than zero"); @@ -51,8 +50,7 @@ public class ThreeJugsRegular { // each possible input; each extra transition is from state zero // to state zero. This allows us to continue even if we hit a // non-accepted input. - int[][] d2 = new int [Q + 1] - []; + int[][] d2 = new int [Q + 1][]; for (int i = 0; i <= Q; i++) { int[] row = new int[S]; for (int j = 0; j < S; j++) { @@ -66,9 +64,7 @@ public class ThreeJugsRegular { } int[] d2_flatten = - (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) - select d2 [i] - [j]) + (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) select d2[i][j]) .ToArray(); // If x has index set m..n, then a[m-1] holds the initial state @@ -80,8 +76,7 @@ public class ThreeJugsRegular { IntVar[] a = solver.MakeIntVarArray(n + 1 - m, 0, Q + 1, "a"); // Check that the final state is in F - solver.Add(a [a.Length - 1] - .Member(F)); + solver.Add(a[a.Length - 1].Member(F)); // First state is q0 solver.Add(a[m] == q0); @@ -126,7 +121,7 @@ public class ThreeJugsRegular { int n_states = 14; int input_max = 15; int initial_state = 1; // state 0 is for the failing state - int[] accepting_states = {15}; + int[] accepting_states = { 15 }; // // Manually crafted DFA @@ -157,29 +152,28 @@ public class ThreeJugsRegular { // However, the DFA is easy to create from adjacency lists. // int[][] states = { - new int[]{2, 9}, // state 1 - new int[]{3}, // state 2 - new int[]{4, 9}, // state 3 - new int[]{5}, // state 4 - new int[]{6, 9}, // state 5 - new int[]{7}, // state 6 - new int[]{8, 9}, // state 7 - new int[]{15}, // state 8 - new int[]{10}, // state 9 - new int[]{11}, // state 10 - new int[]{12}, // state 11 - new int[]{13}, // state 12 - new int[]{14}, // state 13 - new int[]{15} // state 14 + new int[] { 2, 9 }, // state 1 + new int[] { 3 }, // state 2 + new int[] { 4, 9 }, // state 3 + new int[] { 5 }, // state 4 + new int[] { 6, 9 }, // state 5 + new int[] { 7 }, // state 6 + new int[] { 8, 9 }, // state 7 + new int[] { 15 }, // state 8 + new int[] { 10 }, // state 9 + new int[] { 11 }, // state 10 + new int[] { 12 }, // state 11 + new int[] { 13 }, // state 12 + new int[] { 14 }, // state 13 + new int[] { 15 } // state 14 }; - int[, ] transition_fn = new int[n_states, input_max]; + int[,] transition_fn = new int[n_states, input_max]; for (int i = 0; i < n_states; i++) { for (int j = 1; j <= input_max; j++) { bool in_states = false; for (int s = 0; s < states[i].Length; s++) { - if (j == states [i] - [s]) { + if (j == states[i][s]) { in_states = true; break; } @@ -197,21 +191,21 @@ public class ThreeJugsRegular { // the solution. // string[] nodes = { - "8,0,0", // 1 start - "5,0,3", // 2 - "5,3,0", // 3 - "2,3,3", // 4 - "2,5,1", // 5 - "7,0,1", // 6 - "7,1,0", // 7 - "4,1,3", // 8 - "3,5,0", // 9 - "3,2,3", // 10 - "6,2,0", // 11 - "6,0,2", // 12 - "1,5,2", // 13 - "1,4,3", // 14 - "4,4,0" // 15 goal + "8,0,0", // 1 start + "5,0,3", // 2 + "5,3,0", // 3 + "2,3,3", // 4 + "2,5,1", // 5 + "7,0,1", // 6 + "7,1,0", // 7 + "4,1,3", // 8 + "3,5,0", // 9 + "3,2,3", // 10 + "6,2,0", // 11 + "6,0,2", // 12 + "1,5,2", // 13 + "1,4,3", // 14 + "4,4,0" // 15 goal }; // @@ -224,14 +218,12 @@ public class ThreeJugsRegular { // // Constraints // - MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, - accepting_states); + MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, accepting_states); // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -243,9 +235,7 @@ public class ThreeJugsRegular { Console.WriteLine("{0} -> {1}", nodes[0], nodes[x_val[0]]); for (int i = 1; i < n; i++) { // Note: here we subtract 1 to get 0..1 - int val = (int) x [i] - .Value() - - 1; + int val = (int)x[i].Value() - 1; x_val[i] = val; Console.WriteLine("{0} -> {1}", nodes[x_val[i - 1]], nodes[x_val[i]]); } diff --git a/examples/contrib/a_puzzle.cs b/examples/contrib/a_puzzle.cs index 43fee86dba..39b9a407c7 100644 --- a/examples/contrib/a_puzzle.cs +++ b/examples/contrib/a_puzzle.cs @@ -107,7 +107,7 @@ public class APuzzle { IntVar x8 = solver.MakeIntVar(0, n - 1, "x8"); IntVar x9 = solver.MakeIntVar(0, n - 1, "x9"); - IntVar[] all = {x0, x1, x2, x3, x4, x5, x6, x7, x8, x9}; + IntVar[] all = { x0, x1, x2, x3, x4, x5, x6, x7, x8, x9 }; // The unknown, i.e. 2581 = x IntVar x = solver.MakeIntVar(0, n - 1, "x"); @@ -149,17 +149,17 @@ public class APuzzle { } else if (p == 2) { // Another representation of Problem 1 - int[, ] problem1 = { - {8, 8, 0, 9, 6}, {7, 1, 1, 1, 0}, {2, 1, 7, 2, 0}, {6, 6, 6, 6, 4}, - {1, 1, 1, 1, 0}, {3, 2, 1, 3, 0}, {7, 6, 6, 2, 2}, {9, 3, 1, 2, 1}, - {0, 0, 0, 0, 4}, {2, 2, 2, 2, 0}, {3, 3, 3, 3, 0}, {5, 5, 5, 5, 0}, - {8, 1, 9, 3, 3}, {8, 0, 9, 6, 5}, {7, 7, 7, 7, 0}, {9, 9, 9, 9, 4}, - {7, 7, 5, 6, 1}, {6, 8, 5, 5, 3}, {9, 8, 8, 1, 5}, {5, 5, 3, 1, 0}}; + int[,] problem1 = { { 8, 8, 0, 9, 6 }, { 7, 1, 1, 1, 0 }, { 2, 1, 7, 2, 0 }, + { 6, 6, 6, 6, 4 }, { 1, 1, 1, 1, 0 }, { 3, 2, 1, 3, 0 }, + { 7, 6, 6, 2, 2 }, { 9, 3, 1, 2, 1 }, { 0, 0, 0, 0, 4 }, + { 2, 2, 2, 2, 0 }, { 3, 3, 3, 3, 0 }, { 5, 5, 5, 5, 0 }, + { 8, 1, 9, 3, 3 }, { 8, 0, 9, 6, 5 }, { 7, 7, 7, 7, 0 }, + { 9, 9, 9, 9, 4 }, { 7, 7, 5, 6, 1 }, { 6, 8, 5, 5, 3 }, + { 9, 8, 8, 1, 5 }, { 5, 5, 3, 1, 0 } }; for (int i = 0; i < problem1.GetLength(0); i++) { - solver.Add((from j in Enumerable.Range(0, 4) select all[problem1[i, j]]) - .ToArray() - .Sum() == problem1[i, 4]); + solver.Add((from j in Enumerable.Range(0, 4) select all[problem1[i, j]]).ToArray().Sum() == + problem1[i, 4]); } solver.Add(all[2] + all[5] + all[8] + all[1] == x); @@ -180,14 +180,13 @@ public class APuzzle { } else { // Another representation of Problem 2 - int[, ] problem2 = {{8, 8, 0, 9, 6}, {7, 6, 6, 2, 2}, {9, 3, 1, 2, 1}, - {8, 1, 9, 3, 3}, {8, 0, 9, 6, 5}, {7, 7, 5, 6, 1}, - {6, 8, 5, 5, 3}, {9, 8, 8, 1, 5}}; + int[,] problem2 = { { 8, 8, 0, 9, 6 }, { 7, 6, 6, 2, 2 }, { 9, 3, 1, 2, 1 }, + { 8, 1, 9, 3, 3 }, { 8, 0, 9, 6, 5 }, { 7, 7, 5, 6, 1 }, + { 6, 8, 5, 5, 3 }, { 9, 8, 8, 1, 5 } }; for (int i = 0; i < problem2.GetLength(0); i++) { - solver.Add((from j in Enumerable.Range(0, 4) select all[problem2[i, j]]) - .ToArray() - .Sum() == problem2[i, 4]); + solver.Add((from j in Enumerable.Range(0, 4) select all[problem2[i, j]]).ToArray().Sum() == + problem2[i, 4]); } solver.Add(all[2] + all[5] + all[8] + all[1] == x); @@ -196,16 +195,13 @@ public class APuzzle { // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: {0} x0..x9: ", x.Value()); for (int i = 0; i < n; i++) { - Console.Write(all [i] - .Value() + - " "); + Console.Write(all[i].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/a_round_of_golf.cs b/examples/contrib/a_round_of_golf.cs index d39bdd2b26..0b912547e9 100644 --- a/examples/contrib/a_round_of_golf.cs +++ b/examples/contrib/a_round_of_golf.cs @@ -140,25 +140,18 @@ public class ARoundOfGolf { // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.WriteLine( "Last name: " + - String.Join( - ", ", - (from i in last_name select i.Value().ToString()).ToArray())); - Console.WriteLine( - "Job : " + - String.Join(", ", - (from i in job select i.Value().ToString()).ToArray())); - Console.WriteLine( - "Score : " + - String.Join(", ", - (from i in score select i.Value().ToString()).ToArray())); + String.Join(", ", (from i in last_name select i.Value().ToString()).ToArray())); + Console.WriteLine("Job : " + + String.Join(", ", (from i in job select i.Value().ToString()).ToArray())); + Console.WriteLine("Score : " + + String.Join(", ", (from i in score select i.Value().ToString()).ToArray())); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); @@ -169,5 +162,7 @@ public class ARoundOfGolf { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/all_interval.cs b/examples/contrib/all_interval.cs index bf1cd8ac39..31d3f10bbd 100644 --- a/examples/contrib/all_interval.cs +++ b/examples/contrib/all_interval.cs @@ -43,8 +43,7 @@ public class AllInterval { for (int k = 0; k < n - 1; k++) { // solver.Add(diffs[k] == (x[k + 1] - x[k]).Abs()); - solver.Add(diffs[k] == (x[k + 1] - x [k] - .Abs())); + solver.Add(diffs[k] == (x[k + 1] - x[k].Abs())); } // symmetry breaking @@ -54,21 +53,18 @@ public class AllInterval { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", x [i] - .Value()); + Console.Write("{0} ", x[i].Value()); } Console.Write(" diffs: "); for (int i = 0; i < n - 1; i++) { - Console.Write("{0} ", diffs [i] - .Value()); + Console.Write("{0} ", diffs[i].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/alldifferent_except_0.cs b/examples/contrib/alldifferent_except_0.cs index 00982d439e..c35c681d02 100644 --- a/examples/contrib/alldifferent_except_0.cs +++ b/examples/contrib/alldifferent_except_0.cs @@ -66,15 +66,13 @@ public class AllDifferentExcept0Test { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("z: {0} x: ", z.Value()); for (int i = 0; i < n; i++) { - Console.Write("{0} ", x [i] - .Value()); + Console.Write("{0} ", x[i].Value()); } Console.WriteLine(); @@ -88,5 +86,7 @@ public class AllDifferentExcept0Test { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/assignment.cs b/examples/contrib/assignment.cs index a8956b5269..56b2b9b4f5 100644 --- a/examples/contrib/assignment.cs +++ b/examples/contrib/assignment.cs @@ -44,13 +44,14 @@ public class Assignment { // interesting int rows = 4; int cols = 5; - int[, ] cost = { - {14, 5, 8, 7, 15}, {2, 12, 6, 5, 3}, {7, 8, 3, 9, 7}, {2, 4, 6, 10, 1}}; + int[,] cost = { + { 14, 5, 8, 7, 15 }, { 2, 12, 6, 5, 3 }, { 7, 8, 3, 9, 7 }, { 2, 4, 6, 10, 1 } + }; // // Decision variables // - IntVar[, ] x = solver.MakeBoolVarMatrix(rows, cols, "x"); + IntVar[,] x = solver.MakeBoolVarMatrix(rows, cols, "x"); IntVar[] x_flat = x.Flatten(); // @@ -60,25 +61,20 @@ public class Assignment { // Exacly one assignment per row (task), // i.e. all rows must be assigned with one worker for (int i = 0; i < rows; i++) { - solver.Add((from j in Enumerable.Range(0, cols) select x[i, j]) - .ToArray() - .Sum() == 1); + solver.Add((from j in Enumerable.Range(0, cols) select x[i, j]).ToArray().Sum() == 1); } // At most one assignments per column (worker) for (int j = 0; j < cols; j++) { - solver.Add((from i in Enumerable.Range(0, rows) select x[i, j]) - .ToArray() - .Sum() <= 1); + solver.Add((from i in Enumerable.Range(0, rows) select x[i, j]).ToArray().Sum() <= 1); } // Total cost - IntVar total_cost = - (from i in Enumerable.Range(0, rows) from j in Enumerable.Range(0, cols) - select(cost[i, j] * x[i, j])) - .ToArray() - .Sum() - .Var(); + IntVar total_cost = (from i in Enumerable.Range(0, rows) from j in Enumerable.Range(0, cols) + select(cost[i, j] * x[i, j])) + .ToArray() + .Sum() + .Var(); // // objective @@ -88,8 +84,7 @@ public class Assignment { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); @@ -97,9 +92,7 @@ public class Assignment { Console.WriteLine("total_cost: {0}", total_cost.Value()); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } @@ -108,8 +101,7 @@ public class Assignment { for (int i = 0; i < rows; i++) { Console.Write("Task " + i); for (int j = 0; j < cols; j++) { - if (x [i, j] - .Value() == 1) { + if (x[i, j].Value() == 1) { Console.WriteLine(" is done by " + j); } } @@ -125,5 +117,7 @@ public class Assignment { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/broken_weights.cs b/examples/contrib/broken_weights.cs index 34a3e39811..0a0a90e473 100644 --- a/examples/contrib/broken_weights.cs +++ b/examples/contrib/broken_weights.cs @@ -58,7 +58,7 @@ public class BrokenWeights { // IntVar[] weights = solver.MakeIntVarArray(n, 1, m, "weights"); - IntVar[, ] x = new IntVar[m, n]; + IntVar[,] x = new IntVar[m, n]; // Note: in x_flat we insert the weights array before x IntVar[] x_flat = new IntVar[m * n + n]; for (int j = 0; j < n; j++) { @@ -90,30 +90,27 @@ public class BrokenWeights { // -1 is the weights on the left and 1 is on the right. // for (int i = 0; i < m; i++) { - solver.Add((from j in Enumerable.Range(0, n) select weights[j] * x[i, j]) - .ToArray() - .Sum() == i + 1); + solver.Add((from j in Enumerable.Range(0, n) select weights[j] * x[i, j]).ToArray().Sum() == + i + 1); } // // The objective is to minimize the last weight. // - OptimizeVar obj = weights [n - 1] - .Minimize(1); + OptimizeVar obj = weights[n - 1].Minimize(1); // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.Write("weights: "); for (int i = 0; i < n; i++) { - Console.Write("{0,3} ", weights [i] - .Value()); + Console.Write("{0,3} ", weights[i].Value()); } Console.WriteLine(); for (int i = 0; i < 10 + n * 4; i++) { @@ -123,8 +120,7 @@ public class BrokenWeights { for (int i = 0; i < m; i++) { Console.Write("weight {0,2}:", i + 1); for (int j = 0; j < n; j++) { - Console.Write("{0,3} ", x [i, j] - .Value()); + Console.Write("{0,3} ", x[i, j].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/bus_schedule.cs b/examples/contrib/bus_schedule.cs index b711bbb3a4..0d2e77af1c 100644 --- a/examples/contrib/bus_schedule.cs +++ b/examples/contrib/bus_schedule.cs @@ -41,7 +41,7 @@ public class BusSchedule { // data // int time_slots = 6; - int[] demands = {8, 10, 7, 12, 4, 4}; + int[] demands = { 8, 10, 7, 12, 4, 4 }; int max_num = demands.Sum(); // @@ -73,8 +73,7 @@ public class BusSchedule { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); if (num_buses_check == 0) { // Minimize num_buses @@ -90,8 +89,7 @@ public class BusSchedule { result = num_buses.Value(); Console.Write("x: "); for (int i = 0; i < time_slots; i++) { - Console.Write("{0,2} ", x [i] - .Value()); + Console.Write("{0,2} ", x[i].Value()); } Console.WriteLine("num_buses: " + num_buses.Value()); } diff --git a/examples/contrib/circuit.cs b/examples/contrib/circuit.cs index 304264d37a..51990ae77b 100644 --- a/examples/contrib/circuit.cs +++ b/examples/contrib/circuit.cs @@ -73,15 +73,13 @@ public class CircuitTest { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write("{0} ", x [i] - .Value()); + Console.Write("{0} ", x[i].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/circuit2.cs b/examples/contrib/circuit2.cs index 139787a2e0..e0a6ef68f5 100644 --- a/examples/contrib/circuit2.cs +++ b/examples/contrib/circuit2.cs @@ -78,21 +78,18 @@ public class CircuitTest2 { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x : "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", x [i] - .Value()); + Console.Write("{0} ", x[i].Value()); } Console.Write("\npath: "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", path [i] - .Value()); + Console.Write("{0} ", path[i].Value()); } Console.WriteLine("\n"); } diff --git a/examples/contrib/coins3.cs b/examples/contrib/coins3.cs index 79cfe4a6a7..896bad38fa 100644 --- a/examples/contrib/coins3.cs +++ b/examples/contrib/coins3.cs @@ -44,7 +44,7 @@ public class Coins3 { // Data // int n = 6; // number of different coins - int[] variables = {1, 2, 5, 10, 25, 50}; + int[] variables = { 1, 2, 5, 10, 25, 50 }; IEnumerable RANGE = Enumerable.Range(0, n); @@ -76,8 +76,8 @@ public class Coins3 { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); @@ -85,9 +85,7 @@ public class Coins3 { Console.WriteLine("num_coins: {0}", num_coins.Value()); Console.Write("x: "); foreach (int i in RANGE) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -100,5 +98,7 @@ public class Coins3 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/coins_grid.cs b/examples/contrib/coins_grid.cs index 8be6ed29e3..e0e385f7a7 100644 --- a/examples/contrib/coins_grid.cs +++ b/examples/contrib/coins_grid.cs @@ -29,7 +29,7 @@ public class CoinsGrid { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 0, 1, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, 1, "x"); IntVar[] x_flat = x.Flatten(); // @@ -65,8 +65,8 @@ public class CoinsGrid { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); @@ -74,9 +74,7 @@ public class CoinsGrid { Console.WriteLine("obj: " + obj_var.Value()); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/combinatorial_auction2.cs b/examples/contrib/combinatorial_auction2.cs index 887ab179b0..f68d4e6d57 100644 --- a/examples/contrib/combinatorial_auction2.cs +++ b/examples/contrib/combinatorial_auction2.cs @@ -44,15 +44,15 @@ public class CombinatorialAuction2 { // the items for each bid int[][] items = { - new int[]{0, 1}, // A,B - new int[]{0, 2}, // A, C - new int[]{1, 3}, // B,D - new int[]{1, 2, 3}, // B,C,D - new int[]{0} // A + new int[] { 0, 1 }, // A,B + new int[] { 0, 2 }, // A, C + new int[] { 1, 3 }, // B,D + new int[] { 1, 2, 3 }, // B,C,D + new int[] { 0 } // A }; - int[] bid_ids = {0, 1, 2, 3}; - int[] bid_amount = {10, 20, 30, 40, 14}; + int[] bid_ids = { 0, 1, 2, 3 }; + int[] bid_amount = { 10, 20, 30, 40, 14 }; // // Decision variables @@ -81,17 +81,14 @@ public class CombinatorialAuction2 { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.Write("z: {0,2} x: ", z.Value()); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -104,5 +101,7 @@ public class CombinatorialAuction2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/contiguity_regular.cs b/examples/contrib/contiguity_regular.cs index 0ec9d752f1..ad825ee77d 100644 --- a/examples/contrib/contiguity_regular.cs +++ b/examples/contrib/contiguity_regular.cs @@ -42,8 +42,7 @@ public class ContiguityRegular { * F : accepting states * */ - static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[, ] d, - int q0, int[] F) { + static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[,] d, int q0, int[] F) { Debug.Assert(Q > 0, "regular: 'Q' must be greater than zero"); Debug.Assert(S > 0, "regular: 'S' must be greater than zero"); @@ -51,8 +50,7 @@ public class ContiguityRegular { // each possible input; each extra transition is from state zero // to state zero. This allows us to continue even if we hit a // non-accepted input. - int[][] d2 = new int [Q + 1] - []; + int[][] d2 = new int [Q + 1][]; for (int i = 0; i <= Q; i++) { int[] row = new int[S]; for (int j = 0; j < S; j++) { @@ -66,9 +64,7 @@ public class ContiguityRegular { } int[] d2_flatten = - (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) - select d2 [i] - [j]) + (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) select d2[i][j]) .ToArray(); // If x has index set m..n, then a[m-1] holds the initial state @@ -80,8 +76,7 @@ public class ContiguityRegular { IntVar[] a = solver.MakeIntVarArray(n + 1 - m, 0, Q + 1, "a"); // Check that the final state is in F - solver.Add(a [a.Length - 1] - .Member(F)); + solver.Add(a[a.Length - 1].Member(F)); // First state is q0 solver.Add(a[m] == q0); @@ -101,18 +96,16 @@ public class ContiguityRegular { // in MyRegular // all states are accepting states - int[] accepting_states = {1, 2, 3}; + int[] accepting_states = { 1, 2, 3 }; // The regular expression 0*1*0* - int[, ] transition_fn = { - {1, - 2}, // state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0* - {3, 2}, // state 2: 1* - {3, 0}, // state 3: 0* + int[,] transition_fn = { + { 1, 2 }, // state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0* + { 3, 2 }, // state 2: 1* + { 3, 0 }, // state 3: 0* }; - MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, - accepting_states); + MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, accepting_states); } /** @@ -160,18 +153,15 @@ public class ContiguityRegular { // // Search // - DecisionBuilder db = solver.MakePhase( - reg_input, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(reg_input, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { // Note: here we subtract 1 to get 0..1 - Console.Write((reg_input [i] - .Value() - - 1) + - " "); + Console.Write((reg_input[i].Value() - 1) + " "); } Console.WriteLine(); } @@ -184,5 +174,7 @@ public class ContiguityRegular { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/contiguity_transition.cs b/examples/contrib/contiguity_transition.cs index 9a8ea34d5a..3af485cfdd 100644 --- a/examples/contrib/contiguity_transition.cs +++ b/examples/contrib/contiguity_transition.cs @@ -25,12 +25,12 @@ public class ContiguityRegular { int initial_state = 1; // all states are accepting states - int[] accepting_states = {1, 2, 3}; + int[] accepting_states = { 1, 2, 3 }; // The regular expression 0*1*0* {state, input, next state} - long[][] transition_tuples = {new long[]{1, 0, 1}, new long[]{1, 1, 2}, - new long[]{2, 0, 3}, new long[]{2, 1, 2}, - new long[]{3, 0, 3}}; + long[][] transition_tuples = { new long[] { 1, 0, 1 }, new long[] { 1, 1, 2 }, + new long[] { 2, 0, 3 }, new long[] { 2, 1, 2 }, + new long[] { 3, 0, 3 } }; IntTupleSet result = new IntTupleSet(3); result.InsertAll(transition_tuples); @@ -82,16 +82,14 @@ public class ContiguityRegular { // // Search // - DecisionBuilder db = solver.MakePhase( - reg_input, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(reg_input, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write((reg_input [i] - .Value()) + - " "); + Console.Write((reg_input[i].Value()) + " "); } Console.WriteLine(); } @@ -104,5 +102,7 @@ public class ContiguityRegular { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/costas_array.cs b/examples/contrib/costas_array.cs index af85b3a5e2..0caa09bf88 100644 --- a/examples/contrib/costas_array.cs +++ b/examples/contrib/costas_array.cs @@ -52,8 +52,7 @@ public class CostasArray { // Decision variables // IntVar[] costas = solver.MakeIntVarArray(n, 1, n, "costas"); - IntVar[, ] differences = - solver.MakeIntVarMatrix(n, n, -n + 1, n - 1, "differences"); + IntVar[,] differences = solver.MakeIntVarMatrix(n, n, -n + 1, n - 1, "differences"); // // Constraints @@ -119,22 +118,20 @@ public class CostasArray { // // Search // - DecisionBuilder db = solver.MakePhase(costas, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(costas, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("costas: "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", costas [i] - .Value()); + Console.Write("{0} ", costas[i].Value()); } Console.WriteLine("\ndifferences:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - long v = differences [i, j] - .Value(); + long v = differences[i, j].Value(); if (v == -n + 1) { Console.Write(" "); } else { diff --git a/examples/contrib/covering_opl.cs b/examples/contrib/covering_opl.cs index bd3070f981..02d79b0304 100644 --- a/examples/contrib/covering_opl.cs +++ b/examples/contrib/covering_opl.cs @@ -37,24 +37,24 @@ public class SetCoveringOPL { // Which worker is qualified for each task. // Note: This is 1-based and will be made 0-base below. - int[][] qualified = {new int[]{1, 9, 19, 22, 25, 28, 31}, - new int[]{2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32}, - new int[]{3, 10, 19, 24, 26, 30, 32}, - new int[]{4, 21, 25, 28, 32}, - new int[]{5, 11, 16, 22, 23, 27, 31}, - new int[]{6, 20, 24, 26, 30, 32}, - new int[]{7, 12, 17, 25, 30, 31}, - new int[]{8, 17, 20, 22, 23}, - new int[]{9, 13, 14, 26, 29, 30, 31}, - new int[]{10, 21, 25, 31, 32}, - new int[]{14, 15, 18, 23, 24, 27, 30, 32}, - new int[]{18, 19, 22, 24, 26, 29, 31}, - new int[]{11, 20, 25, 28, 30, 32}, - new int[]{16, 19, 23, 31}, - new int[]{9, 18, 26, 28, 31, 32}}; + int[][] qualified = { new int[] { 1, 9, 19, 22, 25, 28, 31 }, + new int[] { 2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32 }, + new int[] { 3, 10, 19, 24, 26, 30, 32 }, + new int[] { 4, 21, 25, 28, 32 }, + new int[] { 5, 11, 16, 22, 23, 27, 31 }, + new int[] { 6, 20, 24, 26, 30, 32 }, + new int[] { 7, 12, 17, 25, 30, 31 }, + new int[] { 8, 17, 20, 22, 23 }, + new int[] { 9, 13, 14, 26, 29, 30, 31 }, + new int[] { 10, 21, 25, 31, 32 }, + new int[] { 14, 15, 18, 23, 24, 27, 30, 32 }, + new int[] { 18, 19, 22, 24, 26, 29, 31 }, + new int[] { 11, 20, 25, 28, 30, 32 }, + new int[] { 16, 19, 23, 31 }, + new int[] { 9, 18, 26, 28, 31, 32 } }; - int[] cost = {1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, - 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9}; + int[] cost = { 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, + 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9 }; // // Decision variables @@ -72,10 +72,7 @@ public class SetCoveringOPL { int len = qualified[j].Length; IntVar[] tmp = new IntVar[len]; for (int c = 0; c < len; c++) { - tmp[c] = hire [qualified [j] - [c] - - 1] - ; + tmp[c] = hire[qualified[j][c] - 1]; } solver.Add(tmp.Sum() >= 1); } @@ -88,8 +85,8 @@ public class SetCoveringOPL { // // Search // - DecisionBuilder db = solver.MakePhase(hire, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(hire, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, objective); @@ -97,8 +94,7 @@ public class SetCoveringOPL { Console.WriteLine("Cost: " + total_cost.Value()); Console.Write("Hire: "); for (int i = 0; i < num_workers; i++) { - if (hire [i] - .Value() == 1) { + if (hire[i].Value() == 1) { Console.Write(i + " "); } } @@ -113,5 +109,7 @@ public class SetCoveringOPL { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/crew.cs b/examples/contrib/crew.cs index 72992567b6..71561df59a 100644 --- a/examples/contrib/crew.cs +++ b/examples/contrib/crew.cs @@ -44,38 +44,37 @@ public class Crew { // // Data // - string[] names = {"Tom", "David", "Jeremy", "Ron", "Joe", - "Bill", "Fred", "Bob", "Mario", "Ed", - "Carol", "Janet", "Tracy", "Marilyn", "Carolyn", - "Cathy", "Inez", "Jean", "Heather", "Juliet"}; + string[] names = { "Tom", "David", "Jeremy", "Ron", "Joe", "Bill", "Fred", + "Bob", "Mario", "Ed", "Carol", "Janet", "Tracy", "Marilyn", + "Carolyn", "Cathy", "Inez", "Jean", "Heather", "Juliet" }; int num_persons = names.Length; // // Attributes of the crew // - int[, ] attributes = { - // steward, hostess, french, spanish, german - {1, 0, 0, 0, 1}, // Tom = 0 - {1, 0, 0, 0, 0}, // David = 1 - {1, 0, 0, 0, 1}, // Jeremy = 2 - {1, 0, 0, 0, 0}, // Ron = 3 - {1, 0, 0, 1, 0}, // Joe = 4 - {1, 0, 1, 1, 0}, // Bill = 5 - {1, 0, 0, 1, 0}, // Fred = 6 - {1, 0, 0, 0, 0}, // Bob = 7 - {1, 0, 0, 1, 1}, // Mario = 8 - {1, 0, 0, 0, 0}, // Ed = 9 - {0, 1, 0, 0, 0}, // Carol = 10 - {0, 1, 0, 0, 0}, // Janet = 11 - {0, 1, 0, 0, 0}, // Tracy = 12 - {0, 1, 0, 1, 1}, // Marilyn = 13 - {0, 1, 0, 0, 0}, // Carolyn = 14 - {0, 1, 0, 0, 0}, // Cathy = 15 - {0, 1, 1, 1, 1}, // Inez = 16 - {0, 1, 1, 0, 0}, // Jean = 17 - {0, 1, 0, 1, 1}, // Heather = 18 - {0, 1, 1, 0, 0} // Juliet = 19 + int[,] attributes = { + // steward, hostess, french, spanish, german + { 1, 0, 0, 0, 1 }, // Tom = 0 + { 1, 0, 0, 0, 0 }, // David = 1 + { 1, 0, 0, 0, 1 }, // Jeremy = 2 + { 1, 0, 0, 0, 0 }, // Ron = 3 + { 1, 0, 0, 1, 0 }, // Joe = 4 + { 1, 0, 1, 1, 0 }, // Bill = 5 + { 1, 0, 0, 1, 0 }, // Fred = 6 + { 1, 0, 0, 0, 0 }, // Bob = 7 + { 1, 0, 0, 1, 1 }, // Mario = 8 + { 1, 0, 0, 0, 0 }, // Ed = 9 + { 0, 1, 0, 0, 0 }, // Carol = 10 + { 0, 1, 0, 0, 0 }, // Janet = 11 + { 0, 1, 0, 0, 0 }, // Tracy = 12 + { 0, 1, 0, 1, 1 }, // Marilyn = 13 + { 0, 1, 0, 0, 0 }, // Carolyn = 14 + { 0, 1, 0, 0, 0 }, // Cathy = 15 + { 0, 1, 1, 1, 1 }, // Inez = 16 + { 0, 1, 1, 0, 0 }, // Jean = 17 + { 0, 1, 0, 1, 1 }, // Heather = 18 + { 0, 1, 1, 0, 0 } // Juliet = 19 }; // @@ -89,13 +88,13 @@ public class Crew { // spanish : How many Spanish speaking employees are required // german : How many German speaking employees are required // - int[, ] required_crew = { - {4, 1, 1, 1, 1, 1}, // Flight 1 - {5, 1, 1, 1, 1, 1}, // Flight 2 - {5, 1, 1, 1, 1, 1}, // .. - {6, 2, 2, 1, 1, 1}, {7, 3, 3, 1, 1, 1}, {4, 1, 1, 1, 1, 1}, - {5, 1, 1, 1, 1, 1}, {6, 1, 1, 1, 1, 1}, {6, 2, 2, 1, 1, 1}, // ... - {7, 3, 3, 1, 1, 1} // Flight 10 + int[,] required_crew = { + { 4, 1, 1, 1, 1, 1 }, // Flight 1 + { 5, 1, 1, 1, 1, 1 }, // Flight 2 + { 5, 1, 1, 1, 1, 1 }, // .. + { 6, 2, 2, 1, 1, 1 }, { 7, 3, 3, 1, 1, 1 }, { 4, 1, 1, 1, 1, 1 }, + { 5, 1, 1, 1, 1, 1 }, { 6, 1, 1, 1, 1, 1 }, { 6, 2, 2, 1, 1, 1 }, // ... + { 7, 3, 3, 1, 1, 1 } // Flight 10 }; int num_flights = required_crew.GetLength(0); @@ -103,8 +102,7 @@ public class Crew { // // Decision variables // - IntVar[, ] crew = - solver.MakeIntVarMatrix(num_flights, num_persons, 0, 1, "crew"); + IntVar[,] crew = solver.MakeIntVarMatrix(num_flights, num_persons, 0, 1, "crew"); IntVar[] crew_flat = crew.Flatten(); // number of working persons @@ -164,8 +162,8 @@ public class Crew { // // Search // - DecisionBuilder db = solver.MakePhase( - crew_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(crew_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); if (minimize > 0) { OptimizeVar obj = num_working.Minimize(1); @@ -182,9 +180,7 @@ public class Crew { for (int f = 0; f < num_flights; f++) { for (int p = 0; p < num_persons; p++) { - Console.Write(crew [f, p] - .Value() + - " "); + Console.Write(crew[f, p].Value() + " "); } Console.WriteLine(); } @@ -192,8 +188,7 @@ public class Crew { for (int f = 0; f < num_flights; f++) { Console.Write("Flight #{0}: ", f); for (int p = 0; p < num_persons; p++) { - if (crew [f, p] - .Value() == 1) { + if (crew[f, p].Value() == 1) { Console.Write(names[p] + " "); } } @@ -204,8 +199,7 @@ public class Crew { for (int p = 0; p < num_persons; p++) { Console.Write("{0,-10}", names[p]); for (int f = 0; f < num_flights; f++) { - if (crew [f, p] - .Value() == 1) { + if (crew[f, p].Value() == 1) { Console.Write(f + " "); } } diff --git a/examples/contrib/crossword.cs b/examples/contrib/crossword.cs index db5111dfdc..a029745de1 100644 --- a/examples/contrib/crossword.cs +++ b/examples/contrib/crossword.cs @@ -37,9 +37,8 @@ public class Crossword { // // data // - String[] alpha = {"_", "a", "b", "c", "d", "e", "f", "g", "h", - "i", "j", "k", "l", "m", "n", "o", "p", "q", - "r", "s", "t", "u", "v", "w", "x", "y", "z"}; + String[] alpha = { "_", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", + "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; int a = 1; int b = 2; @@ -71,38 +70,38 @@ public class Crossword { const int num_words = 15; int word_len = 5; - int[, ] AA = {{h, o, s, e, s}, // HOSES - {l, a, s, e, r}, // LASER - {s, a, i, l, s}, // SAILS - {s, h, e, e, t}, // SHEET - {s, t, e, e, r}, // STEER - {h, e, e, l, 0}, // HEEL - {h, i, k, e, 0}, // HIKE - {k, e, e, l, 0}, // KEEL - {k, n, o, t, 0}, // KNOT - {l, i, n, e, 0}, // LINE - {a, f, t, 0, 0}, // AFT - {a, l, e, 0, 0}, // ALE - {e, e, l, 0, 0}, // EEL - {l, e, e, 0, 0}, // LEE - {t, i, e, 0, 0}}; // TIE + int[,] AA = { { h, o, s, e, s }, // HOSES + { l, a, s, e, r }, // LASER + { s, a, i, l, s }, // SAILS + { s, h, e, e, t }, // SHEET + { s, t, e, e, r }, // STEER + { h, e, e, l, 0 }, // HEEL + { h, i, k, e, 0 }, // HIKE + { k, e, e, l, 0 }, // KEEL + { k, n, o, t, 0 }, // KNOT + { l, i, n, e, 0 }, // LINE + { a, f, t, 0, 0 }, // AFT + { a, l, e, 0, 0 }, // ALE + { e, e, l, 0, 0 }, // EEL + { l, e, e, 0, 0 }, // LEE + { t, i, e, 0, 0 } }; // TIE int num_overlapping = 12; - int[, ] overlapping = {{0, 2, 1, 0}, // s - {0, 4, 2, 0}, // s + int[,] overlapping = { { 0, 2, 1, 0 }, // s + { 0, 4, 2, 0 }, // s - {3, 1, 1, 2}, // i - {3, 2, 4, 0}, // k - {3, 3, 2, 2}, // e + { 3, 1, 1, 2 }, // i + { 3, 2, 4, 0 }, // k + { 3, 3, 2, 2 }, // e - {6, 0, 1, 3}, // l - {6, 1, 4, 1}, // e - {6, 2, 2, 3}, // e + { 6, 0, 1, 3 }, // l + { 6, 1, 4, 1 }, // e + { 6, 2, 2, 3 }, // e - {7, 0, 5, 1}, // l - {7, 2, 1, 4}, // s - {7, 3, 4, 2}, // e - {7, 4, 2, 4}}; // r + { 7, 0, 5, 1 }, // l + { 7, 2, 1, 4 }, // s + { 7, 3, 4, 2 }, // e + { 7, 4, 2, 4 } }; // r int N = 8; @@ -110,7 +109,7 @@ public class Crossword { // Decision variables // // for labeling on A and E - IntVar[, ] A = solver.MakeIntVarMatrix(num_words, word_len, 0, 26, "A"); + IntVar[,] A = solver.MakeIntVarMatrix(num_words, word_len, 0, 26, "A"); IntVar[] A_flat = A.Flatten(); IntVar[] all = new IntVar[(num_words * word_len) + N]; for (int I = 0; I < num_words; I++) { @@ -150,29 +149,24 @@ public class Crossword { // solver.Element(A_flat,E[overlapping[I][2]]*word_len+overlapping[I][3])) // for (int I = 0; I < num_overlapping; I++) { - solver.Add( - A_flat.Element(E[overlapping[I, 0]] * word_len + overlapping[I, 1]) == - A_flat.Element(E[overlapping[I, 2]] * word_len + overlapping[I, 3])); + solver.Add(A_flat.Element(E[overlapping[I, 0]] * word_len + overlapping[I, 1]) == + A_flat.Element(E[overlapping[I, 2]] * word_len + overlapping[I, 3])); } // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.WriteLine("E: "); for (int ee = 0; ee < N; ee++) { - int e_val = (int) E [ee] - .Value(); + int e_val = (int)E[ee].Value(); Console.Write(ee + ": (" + e_val + ") "); for (int ii = 0; ii < word_len; ii++) { - Console.Write(alpha [(int) A [ee, ii] - .Value()] - ); + Console.Write(alpha[(int)A[ee, ii].Value()]); } Console.WriteLine(); } @@ -188,5 +182,7 @@ public class Crossword { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/crypta.cs b/examples/contrib/crypta.cs index ec13f35f2f..292fe5f60b 100644 --- a/examples/contrib/crypta.cs +++ b/examples/contrib/crypta.cs @@ -58,7 +58,7 @@ public class Crypta { IntVar I = solver.MakeIntVar(0, 9, "I"); IntVar J = solver.MakeIntVar(0, 9, "J"); - IntVar[] LD = new IntVar[]{A, B, C, D, E, F, G, H, I, J}; + IntVar[] LD = new IntVar[] { A, B, C, D, E, F, G, H, I, J }; IntVar Sr1 = solver.MakeIntVar(0, 1, "Sr1"); IntVar Sr2 = solver.MakeIntVar(0, 1, "Sr2"); @@ -71,35 +71,30 @@ public class Crypta { solver.Add(D >= 1); solver.Add(G >= 1); - solver.Add((A + 10 * E + 100 * J + 1000 * B + 10000 * B + 100000 * E + - 1000000 * F + E + 10 * J + 100 * E + 1000 * F + 10000 * G + - 100000 * A + 1000000 * F) == - (F + 10 * E + 100 * E + 1000 * H + 10000 * I + 100000 * F + - 1000000 * B + 10000000 * Sr1)); + solver.Add( + (A + 10 * E + 100 * J + 1000 * B + 10000 * B + 100000 * E + 1000000 * F + E + 10 * J + + 100 * E + 1000 * F + 10000 * G + 100000 * A + 1000000 * F) == + (F + 10 * E + 100 * E + 1000 * H + 10000 * I + 100000 * F + 1000000 * B + 10000000 * Sr1)); - solver.Add((C + 10 * F + 100 * H + 1000 * A + 10000 * I + 100000 * I + - 1000000 * J + F + 10 * I + 100 * B + 1000 * D + 10000 * I + - 100000 * D + 1000000 * C + Sr1) == - (J + 10 * F + 100 * A + 1000 * F + 10000 * H + 100000 * D + - 1000000 * D + 10000000 * Sr2)); + solver.Add( + (C + 10 * F + 100 * H + 1000 * A + 10000 * I + 100000 * I + 1000000 * J + F + 10 * I + + 100 * B + 1000 * D + 10000 * I + 100000 * D + 1000000 * C + Sr1) == + (J + 10 * F + 100 * A + 1000 * F + 10000 * H + 100000 * D + 1000000 * D + 10000000 * Sr2)); - solver.Add((A + 10 * J + 100 * J + 1000 * I + 10000 * A + 100000 * B + B + - 10 * A + 100 * G + 1000 * F + 10000 * H + 100000 * D + Sr2) == + solver.Add((A + 10 * J + 100 * J + 1000 * I + 10000 * A + 100000 * B + B + 10 * A + 100 * G + + 1000 * F + 10000 * H + 100000 * D + Sr2) == (C + 10 * A + 100 * G + 1000 * E + 10000 * J + 100000 * G)); // // Search // - DecisionBuilder db = - solver.MakePhase(LD, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(LD, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < 10; i++) { - Console.Write(LD [i] - .ToString() + - " "); + Console.Write(LD[i].ToString() + " "); } Console.WriteLine(); } @@ -111,5 +106,7 @@ public class Crypta { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/crypto.cs b/examples/contrib/crypto.cs index 7526bb3574..be31d3a474 100644 --- a/examples/contrib/crypto.cs +++ b/examples/contrib/crypto.cs @@ -137,17 +137,15 @@ public class Crypto { // // Search // - DecisionBuilder db = solver.MakePhase(LD, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(LD, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (solver.NextSolution()) { for (int i = 0; i < num_letters; i++) { - Console.WriteLine("{0}: {1,2}", str[i], - LD [i] - .Value()); + Console.WriteLine("{0}: {1,2}", str[i], LD[i].Value()); } Console.WriteLine(); } @@ -159,5 +157,7 @@ public class Crypto { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/csdiet.cs b/examples/contrib/csdiet.cs index 7de1a2b923..cde15a2952 100644 --- a/examples/contrib/csdiet.cs +++ b/examples/contrib/csdiet.cs @@ -28,17 +28,17 @@ public class Diet { Solver solver = new Solver("Diet"); int n = 4; - int[] price = {50, 20, 30, 80}; // in cents + int[] price = { 50, 20, 30, 80 }; // in cents // requirements for each nutrition type - int[] limits = {500, 6, 10, 8}; - string[] products = {"A", "B", "C", "D"}; + int[] limits = { 500, 6, 10, 8 }; + string[] products = { "A", "B", "C", "D" }; // nutritions for each product - int[] calories = {400, 200, 150, 500}; - int[] chocolate = {3, 2, 0, 0}; - int[] sugar = {2, 2, 4, 4}; - int[] fat = {2, 4, 1, 5}; + int[] calories = { 400, 200, 150, 500 }; + int[] chocolate = { 3, 2, 0, 0 }; + int[] sugar = { 2, 2, 4, 4 }; + int[] fat = { 2, 4, 1, 5 }; // // Decision variables @@ -64,17 +64,14 @@ public class Diet { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("cost: {0}", cost.Value()); Console.WriteLine("Products: "); for (int i = 0; i < n; i++) { - Console.WriteLine("{0}: {1}", products[i], - x [i] - .Value()); + Console.WriteLine("{0}: {1}", products[i], x[i].Value()); } Console.WriteLine(); @@ -88,5 +85,7 @@ public class Diet { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/curious_set_of_integers.cs b/examples/contrib/curious_set_of_integers.cs index 992440ab90..65f0a6b20c 100644 --- a/examples/contrib/curious_set_of_integers.cs +++ b/examples/contrib/curious_set_of_integers.cs @@ -73,26 +73,21 @@ public class CuriousSetOfIntegers { // This is the original problem // Which is the fifth number? - int[] v = {1, 3, 8, 120}; - IntVar[] b = (from i in Enumerable - .Range(0, n) select x [i] - .IsMember(v)) - .ToArray(); + int[] v = { 1, 3, 8, 120 }; + IntVar[] b = (from i in Enumerable.Range(0, n) select x[i].IsMember(v)).ToArray(); solver.Add(b.Sum() == 4); // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -105,5 +100,7 @@ public class CuriousSetOfIntegers { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/debruijn.cs b/examples/contrib/debruijn.cs index 6776e50338..d0d75dbf40 100644 --- a/examples/contrib/debruijn.cs +++ b/examples/contrib/debruijn.cs @@ -29,7 +29,7 @@ public class DeBruijn { IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { - tmp[i] = (a[i] * (int) Math.Pow(bbase, (len - i - 1))).Var(); + tmp[i] = (a[i] * (int)Math.Pow(bbase, (len - i - 1))).Var(); } return tmp.Sum() == num; } @@ -50,9 +50,8 @@ public class DeBruijn { // // Decision variables // - IntVar[] x = - solver.MakeIntVarArray(m, 0, (int) Math.Pow(bbase, n) - 1, "x"); - IntVar[, ] binary = solver.MakeIntVarMatrix(m, n, 0, bbase - 1, "binary"); + IntVar[] x = solver.MakeIntVarArray(m, 0, (int)Math.Pow(bbase, n) - 1, "x"); + IntVar[,] binary = solver.MakeIntVarMatrix(m, n, 0, bbase - 1, "binary"); // this is the de Bruijn sequence IntVar[] bin_code = solver.MakeIntVarArray(m, 0, bbase - 1, "bin_code"); @@ -121,31 +120,25 @@ public class DeBruijn { // // Search // - DecisionBuilder db = solver.MakePhase( - all, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(all, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < m; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.Write("\nde Bruijn sequence:"); for (int i = 0; i < m; i++) { - Console.Write(bin_code [i] - .Value() + - " "); + Console.Write(bin_code[i].Value() + " "); } Console.Write("\ngcc: "); for (int i = 0; i < bbase; i++) { - Console.Write(gcc [i] - .Value() + - " "); + Console.Write(gcc[i].Value() + " "); } Console.WriteLine("\n"); diff --git a/examples/contrib/discrete_tomography.cs b/examples/contrib/discrete_tomography.cs index 4c9e843911..4ca2a03eb8 100644 --- a/examples/contrib/discrete_tomography.cs +++ b/examples/contrib/discrete_tomography.cs @@ -22,8 +22,8 @@ using Google.OrTools.ConstraintSolver; public class DiscreteTomography { // default problem - static int[] default_rowsums = {0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0}; - static int[] default_colsums = {0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0}; + static int[] default_rowsums = { 0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0 }; + static int[] default_colsums = { 0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0 }; static int[] rowsums2; static int[] colsums2; @@ -84,7 +84,7 @@ public class DiscreteTomography { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(r, c, 0, 1, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(r, c, 0, 1, "x"); IntVar[] x_flat = x.Flatten(); // @@ -106,18 +106,15 @@ public class DiscreteTomography { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { - Console.Write("{0} ", x [i, j] - .Value() == 1 - ? "#" - : "."); + Console.Write("{0} ", x[i, j].Value() == 1 ? "#" : "."); } Console.WriteLine(); } diff --git a/examples/contrib/divisible_by_9_through_1.cs b/examples/contrib/divisible_by_9_through_1.cs index bde7046590..f1a07340eb 100644 --- a/examples/contrib/divisible_by_9_through_1.cs +++ b/examples/contrib/divisible_by_9_through_1.cs @@ -36,8 +36,8 @@ public class DivisibleBy9Through1 { long ubx = x.Max(); long ubx_neg = -ubx; long lbx_neg = -lbx; - int min_x = (int) Math.Min(lbx, ubx_neg); - int max_x = (int) Math.Max(ubx, lbx_neg); + int min_x = (int)Math.Min(lbx, ubx_neg); + int max_x = (int)Math.Max(ubx, lbx_neg); IntVar d = solver.MakeIntVar(min_x, max_x, "d"); @@ -75,7 +75,7 @@ public class DivisibleBy9Through1 { IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { - tmp[i] = (a[i] * (int) Math.Pow(bbase, (len - i - 1))).Var(); + tmp[i] = (a[i] * (int)Math.Pow(bbase, (len - i - 1))).Var(); } return tmp.Sum() == num; } @@ -89,11 +89,10 @@ public class DivisibleBy9Through1 { private static void Solve(int bbase) { Solver solver = new Solver("DivisibleBy9Through1"); - int m = (int) Math.Pow(bbase, (bbase - 1)) - 1; + int m = (int)Math.Pow(bbase, (bbase - 1)) - 1; int n = bbase - 1; - String[] digits_str = {"_", "0", "1", "2", "3", "4", - "5", "6", "7", "8", "9"}; + String[] digits_str = { "_", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; Console.WriteLine("base: " + bbase); @@ -127,35 +126,26 @@ public class DivisibleBy9Through1 { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine("\nt: "); for (int i = 0; i < n; i++) { - Console.Write(t [i] - .Value() + - " "); + Console.Write(t[i].Value() + " "); } Console.WriteLine("\n"); if (bbase != 10) { - Console.Write("Number base 10: " + t [0] - .Value()); + Console.Write("Number base 10: " + t[0].Value()); Console.Write(" Base " + bbase + ": "); for (int i = 0; i < n; i++) { - Console.Write(digits_str [(int) x [i] - .Value() + - 1] - ); + Console.Write(digits_str[(int)x[i].Value() + 1]); } Console.WriteLine("\n"); } @@ -175,8 +165,7 @@ public class DivisibleBy9Through1 { bbase = Convert.ToInt32(args[0]); if (bbase > 12) { // Though base = 12 has no solution... - Console.WriteLine( - "Sorry, max relevant base is 12. Setting base to 12."); + Console.WriteLine("Sorry, max relevant base is 12. Setting base to 12."); bbase = 10; } } diff --git a/examples/contrib/dudeney.cs b/examples/contrib/dudeney.cs index 1c52a1b817..e026672d26 100644 --- a/examples/contrib/dudeney.cs +++ b/examples/contrib/dudeney.cs @@ -26,7 +26,7 @@ public class DudeneyNumbers { IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { - tmp[i] = (a[i] * (int) Math.Pow(bbase, (len - i - 1))).Var(); + tmp[i] = (a[i] * (int)Math.Pow(bbase, (len - i - 1))).Var(); } return tmp.Sum() == num; } @@ -65,7 +65,7 @@ public class DudeneyNumbers { // Decision variables // IntVar[] x = solver.MakeIntVarArray(n, 0, 9, "x"); - IntVar nb = solver.MakeIntVar(3, (int) Math.Pow(10, n), "nb"); + IntVar nb = solver.MakeIntVar(3, (int)Math.Pow(10, n), "nb"); IntVar s = solver.MakeIntVar(1, 9 * n + 1, "s"); // @@ -77,17 +77,14 @@ public class DudeneyNumbers { // solver.Add(ToNum(x, nb, 10)); // alternative - solver.Add((from i in Enumerable - .Range(0, n) select(x[i] * (int) Math.Pow(10, n - i - 1)) - .Var()) + solver.Add((from i in Enumerable.Range(0, n) select(x[i] * (int)Math.Pow(10, n - i - 1)).Var()) .ToArray() .Sum() == nb); // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); @@ -103,5 +100,7 @@ public class DudeneyNumbers { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/einav_puzzle2.cs b/examples/contrib/einav_puzzle2.cs index 2536a33560..f902ebaa06 100644 --- a/examples/contrib/einav_puzzle2.cs +++ b/examples/contrib/einav_puzzle2.cs @@ -85,33 +85,22 @@ public class EinavPuzzle2 { // Full problem int rows = 27; int cols = 9; - int[, ] data = {{33, 30, 10, -6, 18, -7, -11, 23, -6}, - {16, -19, 9, -26, -8, -19, -8, -21, -14}, - {17, 12, -14, 31, -30, 13, -13, 19, 16}, - {-6, -11, 1, 17, -12, -4, -7, 14, -21}, - {18, -31, 34, -22, 17, -19, 20, 24, 6}, - {33, -18, 17, -15, 31, -5, 3, 27, -3}, - {-18, -20, -18, 31, 6, 4, -2, -12, 24}, - {27, 14, 4, -29, -3, 5, -29, 8, -12}, - {-15, -7, -23, 23, -9, -8, 6, 8, -12}, - {33, -23, -19, -4, -8, -7, 11, -12, 31}, - {-20, 19, -15, -30, 11, 32, 7, 14, -5}, - {-23, 18, -32, -2, -31, -7, 8, 24, 16}, - {32, -4, -10, -14, -6, -1, 0, 23, 23}, - {25, 0, -23, 22, 12, 28, -27, 15, 4}, - {-30, -13, -16, -3, -3, -32, -3, 27, -31}, - {22, 1, 26, 4, -2, -13, 26, 17, 14}, - {-9, -18, 3, -20, -27, -32, -11, 27, 13}, - {-17, 33, -7, 19, -32, 13, -31, -2, -24}, - {-31, 27, -31, -29, 15, 2, 29, -15, 33}, - {-18, -23, 15, 28, 0, 30, -4, 12, -32}, - {-3, 34, 27, -25, -18, 26, 1, 34, 26}, - {-21, -31, -10, -13, -30, -17, -12, -26, 31}, - {23, -31, -19, 21, -17, -10, 2, -23, 23}, - {-3, 6, 0, -3, -32, 0, -10, -25, 14}, - {-19, 9, 14, -27, 20, 15, -5, -27, 18}, - {11, -6, 24, 7, -17, 26, 20, -31, -25}, - {-25, 4, -16, 30, 33, 23, -4, -4, 23}}; + int[,] data = { + { 33, 30, 10, -6, 18, -7, -11, 23, -6 }, { 16, -19, 9, -26, -8, -19, -8, -21, -14 }, + { 17, 12, -14, 31, -30, 13, -13, 19, 16 }, { -6, -11, 1, 17, -12, -4, -7, 14, -21 }, + { 18, -31, 34, -22, 17, -19, 20, 24, 6 }, { 33, -18, 17, -15, 31, -5, 3, 27, -3 }, + { -18, -20, -18, 31, 6, 4, -2, -12, 24 }, { 27, 14, 4, -29, -3, 5, -29, 8, -12 }, + { -15, -7, -23, 23, -9, -8, 6, 8, -12 }, { 33, -23, -19, -4, -8, -7, 11, -12, 31 }, + { -20, 19, -15, -30, 11, 32, 7, 14, -5 }, { -23, 18, -32, -2, -31, -7, 8, 24, 16 }, + { 32, -4, -10, -14, -6, -1, 0, 23, 23 }, { 25, 0, -23, 22, 12, 28, -27, 15, 4 }, + { -30, -13, -16, -3, -3, -32, -3, 27, -31 }, { 22, 1, 26, 4, -2, -13, 26, 17, 14 }, + { -9, -18, 3, -20, -27, -32, -11, 27, 13 }, { -17, 33, -7, 19, -32, 13, -31, -2, -24 }, + { -31, 27, -31, -29, 15, 2, 29, -15, 33 }, { -18, -23, 15, 28, 0, 30, -4, 12, -32 }, + { -3, 34, 27, -25, -18, 26, 1, 34, 26 }, { -21, -31, -10, -13, -30, -17, -12, -26, 31 }, + { 23, -31, -19, 21, -17, -10, 2, -23, 23 }, { -3, 6, 0, -3, -32, 0, -10, -25, 14 }, + { -19, 9, 14, -27, 20, 15, -5, -27, 18 }, { 11, -6, 24, 7, -17, 26, 20, -31, -25 }, + { -25, 4, -16, 30, 33, 23, -4, -4, 23 } + }; IEnumerable ROWS = Enumerable.Range(0, rows); IEnumerable COLS = Enumerable.Range(0, cols); @@ -119,15 +108,13 @@ public class EinavPuzzle2 { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(rows, cols, -100, 100, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(rows, cols, -100, 100, "x"); IntVar[] x_flat = x.Flatten(); - int[] signs_domain = {-1, 1}; + int[] signs_domain = { -1, 1 }; // This don't work at the moment... - IntVar[] row_signs = - solver.MakeIntVarArray(rows, signs_domain, "row_signs"); - IntVar[] col_signs = - solver.MakeIntVarArray(cols, signs_domain, "col_signs"); + IntVar[] row_signs = solver.MakeIntVarArray(rows, signs_domain, "row_signs"); + IntVar[] col_signs = solver.MakeIntVarArray(cols, signs_domain, "col_signs"); // To optimize IntVar total_sum = x_flat.Sum().VarWithName("total_sum"); @@ -142,27 +129,19 @@ public class EinavPuzzle2 { } // row sums - IntVar[] row_sums = (from i in ROWS select(from j in COLS select x[i, j]) - .ToArray() - .Sum() - .Var()) - .ToArray(); + IntVar[] row_sums = + (from i in ROWS select(from j in COLS select x[i, j]).ToArray().Sum().Var()).ToArray(); foreach (int i in ROWS) { - row_sums [i] - .SetMin(0); + row_sums[i].SetMin(0); } // col sums - IntVar[] col_sums = (from j in COLS select(from i in ROWS select x[i, j]) - .ToArray() - .Sum() - .Var()) - .ToArray(); + IntVar[] col_sums = + (from j in COLS select(from i in ROWS select x[i, j]).ToArray().Sum().Var()).ToArray(); foreach (int j in COLS) { - col_sums [j] - .SetMin(0); + col_sums[j].SetMin(0); } // @@ -173,9 +152,9 @@ public class EinavPuzzle2 { // // Search // - DecisionBuilder db = solver.MakePhase(col_signs.Concat(row_signs).ToArray(), - Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(col_signs.Concat(row_signs).ToArray(), Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, + Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); @@ -183,34 +162,25 @@ public class EinavPuzzle2 { Console.WriteLine("Sum: {0}", total_sum.Value()); Console.Write("row_sums: "); foreach (int i in ROWS) { - Console.Write(row_sums [i] - .Value() + - " "); + Console.Write(row_sums[i].Value() + " "); } Console.Write("\nrow_signs: "); foreach (int i in ROWS) { - Console.Write(row_signs [i] - .Value() + - " "); + Console.Write(row_signs[i].Value() + " "); } Console.Write("\ncol_sums: "); foreach (int j in COLS) { - Console.Write(col_sums [j] - .Value() + - " "); + Console.Write(col_sums[j].Value() + " "); } Console.Write("\ncol_signs: "); foreach (int j in COLS) { - Console.Write(col_signs [j] - .Value() + - " "); + Console.Write(col_signs[j].Value() + " "); } Console.WriteLine("\n"); foreach (int i in ROWS) { foreach (int j in COLS) { - Console.Write("{0,3} ", x [i, j] - .Value()); + Console.Write("{0,3} ", x[i, j].Value()); } Console.WriteLine(); } @@ -225,5 +195,7 @@ public class EinavPuzzle2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/eq10.cs b/examples/contrib/eq10.cs index 393ea228eb..643cbc270a 100644 --- a/examples/contrib/eq10.cs +++ b/examples/contrib/eq10.cs @@ -42,17 +42,15 @@ public class Eq10 { IntVar X6 = solver.MakeIntVar(0, 10, "X6"); IntVar X7 = solver.MakeIntVar(0, 10, "X7"); - IntVar[] X = {X1, X2, X3, X4, X5, X6, X7}; + IntVar[] X = { X1, X2, X3, X4, X5, X6, X7 }; // // Constraints // - solver.Add(0 + 98527 * X1 + 34588 * X2 + 5872 * X3 + 59422 * X5 + - 65159 * X7 == + solver.Add(0 + 98527 * X1 + 34588 * X2 + 5872 * X3 + 59422 * X5 + 65159 * X7 == 1547604 + 30704 * X4 + 29649 * X6); - solver.Add(0 + 98957 * X2 + 83634 * X3 + 69966 * X4 + 62038 * X5 + - 37164 * X6 + 85413 * X7 == + solver.Add(0 + 98957 * X2 + 83634 * X3 + 69966 * X4 + 62038 * X5 + 37164 * X6 + 85413 * X7 == 1823553 + 93989 * X1); solver.Add(900032 + 10949 * X1 + 77761 * X2 + 67052 * X5 == @@ -65,15 +63,12 @@ public class Eq10 { 1185471 + 60152 * X1 + 21103 * X2 + 97932 * X6); solver.Add(1394152 + 66920 * X1 + 55679 * X4 == - 0 + 64234 * X2 + 65337 * X3 + 45581 * X5 + 67707 * X6 + - 98038 * X7); + 0 + 64234 * X2 + 65337 * X3 + 45581 * X5 + 67707 * X6 + 98038 * X7); - solver.Add(0 + 68550 * X1 + 27886 * X2 + 31716 * X3 + 73597 * X4 + - 38835 * X7 == + solver.Add(0 + 68550 * X1 + 27886 * X2 + 31716 * X3 + 73597 * X4 + 38835 * X7 == 279091 + 88963 * X5 + 76391 * X6); - solver.Add(0 + 76132 * X2 + 71860 * X3 + 22770 * X4 + 68211 * X5 + - 78587 * X6 == + solver.Add(0 + 76132 * X2 + 71860 * X3 + 22770 * X4 + 68211 * X5 + 78587 * X6 == 480923 + 48224 * X1 + 82817 * X7); solver.Add(519878 + 94198 * X2 + 87234 * X3 + 37498 * X4 == @@ -85,16 +80,13 @@ public class Eq10 { // // Search // - DecisionBuilder db = - solver.MakePhase(X, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(X, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write(X [i] - .ToString() + - " "); + Console.Write(X[i].ToString() + " "); } Console.WriteLine(); } @@ -107,5 +99,7 @@ public class Eq10 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/eq20.cs b/examples/contrib/eq20.cs index 848f669b5f..33228b1c7c 100644 --- a/examples/contrib/eq20.cs +++ b/examples/contrib/eq20.cs @@ -42,85 +42,82 @@ public class Eq20 { IntVar X5 = solver.MakeIntVar(0, 10, "X5"); IntVar X6 = solver.MakeIntVar(0, 10, "X6"); - IntVar[] X = {X0, X1, X2, X3, X4, X5, X6}; + IntVar[] X = { X0, X1, X2, X3, X4, X5, X6 }; // // Constraints // - solver.Add(-76706 * X0 + 98205 * X1 + 23445 * X2 + 67921 * X3 + 24111 * X4 + - -48614 * X5 + -41906 * X6 == + solver.Add(-76706 * X0 + 98205 * X1 + 23445 * X2 + 67921 * X3 + 24111 * X4 + -48614 * X5 + + -41906 * X6 == 821228); - solver.Add(87059 * X0 + -29101 * X1 + -5513 * X2 + -21219 * X3 + - 22128 * X4 + 7276 * X5 + 57308 * X6 == + solver.Add(87059 * X0 + -29101 * X1 + -5513 * X2 + -21219 * X3 + 22128 * X4 + 7276 * X5 + + 57308 * X6 == 22167); - solver.Add(-60113 * X0 + 29475 * X1 + 34421 * X2 + -76870 * X3 + - 62646 * X4 + 29278 * X5 + -15212 * X6 == + solver.Add(-60113 * X0 + 29475 * X1 + 34421 * X2 + -76870 * X3 + 62646 * X4 + 29278 * X5 + + -15212 * X6 == 251591); - solver.Add(49149 * X0 + 52871 * X1 + -7132 * X2 + 56728 * X3 + -33576 * X4 + - -49530 * X5 + -62089 * X6 == + solver.Add(49149 * X0 + 52871 * X1 + -7132 * X2 + 56728 * X3 + -33576 * X4 + -49530 * X5 + + -62089 * X6 == 146074); - solver.Add(-10343 * X0 + 87758 * X1 + -11782 * X2 + 19346 * X3 + - 70072 * X4 + -36991 * X5 + 44529 * X6 == + solver.Add(-10343 * X0 + 87758 * X1 + -11782 * X2 + 19346 * X3 + 70072 * X4 + -36991 * X5 + + 44529 * X6 == 740061); - solver.Add(85176 * X0 + -95332 * X1 + -1268 * X2 + 57898 * X3 + 15883 * X4 + - 50547 * X5 + 83287 * X6 == + solver.Add(85176 * X0 + -95332 * X1 + -1268 * X2 + 57898 * X3 + 15883 * X4 + 50547 * X5 + + 83287 * X6 == 373854); - solver.Add(-85698 * X0 + 29958 * X1 + 57308 * X2 + 48789 * X3 + - -78219 * X4 + 4657 * X5 + 34539 * X6 == + solver.Add(-85698 * X0 + 29958 * X1 + 57308 * X2 + 48789 * X3 + -78219 * X4 + 4657 * X5 + + 34539 * X6 == 249912); - solver.Add(-67456 * X0 + 84750 * X1 + -51553 * X2 + 21239 * X3 + - 81675 * X4 + -99395 * X5 + -4254 * X6 == + solver.Add(-67456 * X0 + 84750 * X1 + -51553 * X2 + 21239 * X3 + 81675 * X4 + -99395 * X5 + + -4254 * X6 == 277271); - solver.Add(94016 * X0 + -82071 * X1 + 35961 * X2 + 66597 * X3 + - -30705 * X4 + -44404 * X5 + -38304 * X6 == + solver.Add(94016 * X0 + -82071 * X1 + 35961 * X2 + 66597 * X3 + -30705 * X4 + -44404 * X5 + + -38304 * X6 == 25334); - solver.Add(-60301 * X0 + 31227 * X1 + 93951 * X2 + 73889 * X3 + 81526 * X4 + - -72702 * X5 + 68026 * X6 == + solver.Add(-60301 * X0 + 31227 * X1 + 93951 * X2 + 73889 * X3 + 81526 * X4 + -72702 * X5 + + 68026 * X6 == 1410723); - solver.Add(-16835 * X0 + 47385 * X1 + 97715 * X2 + -12640 * X3 + - 69028 * X4 + 76212 * X5 + -81102 * X6 == + solver.Add(-16835 * X0 + 47385 * X1 + 97715 * X2 + -12640 * X3 + 69028 * X4 + 76212 * X5 + + -81102 * X6 == 1244857); - solver.Add(-43277 * X0 + 43525 * X1 + 92298 * X2 + 58630 * X3 + 92590 * X4 + - -9372 * X5 + -60227 * X6 == + solver.Add(-43277 * X0 + 43525 * X1 + 92298 * X2 + 58630 * X3 + 92590 * X4 + -9372 * X5 + + -60227 * X6 == 1503588); - solver.Add(-64919 * X0 + 80460 * X1 + 90840 * X2 + -59624 * X3 + - -75542 * X4 + 25145 * X5 + -47935 * X6 == + solver.Add(-64919 * X0 + 80460 * X1 + 90840 * X2 + -59624 * X3 + -75542 * X4 + 25145 * X5 + + -47935 * X6 == 18465); - solver.Add(-45086 * X0 + 51830 * X1 + -4578 * X2 + 96120 * X3 + 21231 * X4 + - 97919 * X5 + 65651 * X6 == + solver.Add(-45086 * X0 + 51830 * X1 + -4578 * X2 + 96120 * X3 + 21231 * X4 + 97919 * X5 + + 65651 * X6 == 1198280); - solver.Add(85268 * X0 + 54180 * X1 + -18810 * X2 + -48219 * X3 + 6013 * X4 + - 78169 * X5 + -79785 * X6 == + solver.Add(85268 * X0 + 54180 * X1 + -18810 * X2 + -48219 * X3 + 6013 * X4 + 78169 * X5 + + -79785 * X6 == 90614); - solver.Add(8874 * X0 + -58412 * X1 + 73947 * X2 + 17147 * X3 + 62335 * X4 + - 16005 * X5 + 8632 * X6 == + solver.Add(8874 * X0 + -58412 * X1 + 73947 * X2 + 17147 * X3 + 62335 * X4 + 16005 * X5 + + 8632 * X6 == 752447); - solver.Add(71202 * X0 + -11119 * X1 + 73017 * X2 + -38875 * X3 + - -14413 * X4 + -29234 * X5 + 72370 * X6 == + solver.Add(71202 * X0 + -11119 * X1 + 73017 * X2 + -38875 * X3 + -14413 * X4 + -29234 * X5 + + 72370 * X6 == 129768); - solver.Add(1671 * X0 + -34121 * X1 + 10763 * X2 + 80609 * X3 + 42532 * X4 + - 93520 * X5 + -33488 * X6 == + solver.Add(1671 * X0 + -34121 * X1 + 10763 * X2 + 80609 * X3 + 42532 * X4 + 93520 * X5 + + -33488 * X6 == 915683); - solver.Add(51637 * X0 + 67761 * X1 + 95951 * X2 + 3834 * X3 + -96722 * X4 + - 59190 * X5 + 15280 * X6 == + solver.Add(51637 * X0 + 67761 * X1 + 95951 * X2 + 3834 * X3 + -96722 * X4 + 59190 * X5 + + 15280 * X6 == 533909); - solver.Add(-16105 * X0 + 62397 * X1 + -6704 * X2 + 43340 * X3 + 95100 * X4 + - -68610 * X5 + 58301 * X6 == + solver.Add(-16105 * X0 + 62397 * X1 + -6704 * X2 + 43340 * X3 + 95100 * X4 + -68610 * X5 + + 58301 * X6 == 876370); // // Search // - DecisionBuilder db = - solver.MakePhase(X, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(X, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write(X [i] - .ToString() + - " "); + Console.Write(X[i].ToString() + " "); } Console.WriteLine(); } @@ -133,5 +130,7 @@ public class Eq20 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/fill_a_pix.cs b/examples/contrib/fill_a_pix.cs index c89439bd44..f95f7026e9 100644 --- a/examples/contrib/fill_a_pix.cs +++ b/examples/contrib/fill_a_pix.cs @@ -30,16 +30,17 @@ public class FillAPix { // static int default_n = 10; - static int[, ] default_puzzle = { - {X, X, X, X, X, X, X, X, 0, X}, {X, 8, 8, X, 2, X, 0, X, X, X}, - {5, X, 8, X, X, X, X, X, X, X}, {X, X, X, X, X, 2, X, X, X, 2}, - {1, X, X, X, 4, 5, 6, X, X, X}, {X, 0, X, X, X, 7, 9, X, X, 6}, - {X, X, X, 6, X, X, 9, X, X, 6}, {X, X, 6, 6, 8, 7, 8, 7, X, 5}, - {X, 4, X, 6, 6, 6, X, 6, X, 4}, {X, X, X, X, X, X, 3, X, X, X}}; + static int[,] default_puzzle = { + { X, X, X, X, X, X, X, X, 0, X }, { X, 8, 8, X, 2, X, 0, X, X, X }, + { 5, X, 8, X, X, X, X, X, X, X }, { X, X, X, X, X, 2, X, X, X, 2 }, + { 1, X, X, X, 4, 5, 6, X, X, X }, { X, 0, X, X, X, 7, 9, X, X, 6 }, + { X, X, X, 6, X, X, 9, X, X, 6 }, { X, X, 6, 6, 8, 7, 8, 7, X, 5 }, + { X, 4, X, 6, 6, 6, X, 6, X, 4 }, { X, X, X, X, X, X, 3, X, X, X } + }; // for the actual problem static int n; - static int[, ] puzzle; + static int[,] puzzle; /** * @@ -75,7 +76,7 @@ public class FillAPix { // // data // - int[] S = {-1, 0, 1}; + int[] S = { -1, 0, 1 }; Console.WriteLine("Problem:"); for (int i = 0; i < n; i++) { @@ -93,7 +94,7 @@ public class FillAPix { // // Decision variables // - IntVar[, ] pict = solver.MakeIntVarMatrix(n, n, 0, 1, "pict"); + IntVar[,] pict = solver.MakeIntVarMatrix(n, n, 0, 1, "pict"); IntVar[] pict_flat = pict.Flatten(); // for branching // @@ -103,8 +104,10 @@ public class FillAPix { for (int j = 0; j < n; j++) { if (puzzle[i, j] > X) { // this cell is the sum of all surrounding cells - var tmp = from a in S from b in S where i + a >= 0 && j + b >= 0 && - i + a < n && j + b < n select(pict[i + a, j + b]); + var tmp = from a in S from b in S + where i + + a >= 0 && j + b >= 0 && + i + a 0 && d[i] > 0 select i) .ToArray(); - int times_min = tasks.Min(i =>(int) s [i] - .Min()); + int times_min = tasks.Min(i => (int)s[i].Min()); int d_max = d.Max(); - int times_max = tasks.Max(i =>(int) s [i] - .Max() + - d_max); + int times_max = tasks.Max(i => (int)s[i].Max() + d_max); for (int t = times_min; t <= times_max; t++) { ArrayList bb = new ArrayList(); foreach (int i in tasks) { @@ -83,17 +79,15 @@ public class FurnitureMoving { Solver solver = new Solver("FurnitureMoving"); int n = 4; - int[] duration = {30, 10, 15, 15}; - int[] demand = {3, 1, 3, 2}; + int[] duration = { 30, 10, 15, 15 }; + int[] demand = { 3, 1, 3, 2 }; int upper_limit = 160; // // Decision variables // - IntVar[] start_times = - solver.MakeIntVarArray(n, 0, upper_limit, "start_times"); - IntVar[] end_times = - solver.MakeIntVarArray(n, 0, upper_limit * 2, "end_times"); + IntVar[] start_times = solver.MakeIntVarArray(n, 0, upper_limit, "start_times"); + IntVar[] end_times = solver.MakeIntVarArray(n, 0, upper_limit * 2, "end_times"); IntVar end_time = solver.MakeIntVar(0, upper_limit * 2, "end_time"); // number of needed resources, to be minimized or constrained @@ -135,23 +129,17 @@ public class FurnitureMoving { // // Search // - DecisionBuilder db = solver.MakePhase( - start_times, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(start_times, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { - Console.WriteLine("num_resources: {0} end_time: {1}", - num_resources.Value(), end_time.Value()); + Console.WriteLine("num_resources: {0} end_time: {1}", num_resources.Value(), + end_time.Value()); for (int i = 0; i < n; i++) { - Console.WriteLine("Task {0,1}: {1,2} -> {2,2} -> {3,2} (demand: {4})", - i, - start_times [i] - .Value(), - duration[i], - end_times [i] - .Value(), - demand[i]); + Console.WriteLine("Task {0,1}: {1,2} -> {2,2} -> {3,2} (demand: {4})", i, + start_times[i].Value(), duration[i], end_times[i].Value(), demand[i]); } Console.WriteLine(); } @@ -164,5 +152,7 @@ public class FurnitureMoving { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/furniture_moving_intervals.cs b/examples/contrib/furniture_moving_intervals.cs index d06d1c2e68..1270eebd76 100644 --- a/examples/contrib/furniture_moving_intervals.cs +++ b/examples/contrib/furniture_moving_intervals.cs @@ -30,8 +30,8 @@ public class FurnitureMovingIntervals { Solver solver = new Solver("FurnitureMovingIntervals"); const int n = 4; - int[] durations = {30, 10, 15, 15}; - int[] demand = {3, 1, 3, 2}; + int[] durations = { 30, 10, 15, 15 }; + int[] demand = { 3, 1, 3, 2 }; const int upper_limit = 160; const int max_num_workers = 5; @@ -40,33 +40,28 @@ public class FurnitureMovingIntervals { // IntervalVar[] tasks = new IntervalVar[n]; for (int i = 0; i < n; ++i) { - tasks[i] = solver.MakeFixedDurationIntervalVar( - 0, upper_limit - durations[i], durations[i], false, "task_" + i); + tasks[i] = solver.MakeFixedDurationIntervalVar(0, upper_limit - durations[i], durations[i], + false, "task_" + i); } // Fillers that span the whole resource and limit the available // number of workers. IntervalVar[] fillers = new IntervalVar[max_num_workers]; for (int i = 0; i < max_num_workers; ++i) { - fillers[i] = solver.MakeFixedDurationIntervalVar(0, 0, upper_limit, true, - "filler_" + i); + fillers[i] = solver.MakeFixedDurationIntervalVar(0, 0, upper_limit, true, "filler_" + i); } // Number of needed resources, to be minimized or constrained. IntVar num_workers = solver.MakeIntVar(0, max_num_workers, "num_workers"); // Links fillers and num_workers. for (int i = 0; i < max_num_workers; ++i) { - solver.Add((num_workers > i) + fillers [i] - .PerformedExpr() == - 1); + solver.Add((num_workers > i) + fillers[i].PerformedExpr() == 1); } // Creates makespan. IntVar[] ends = new IntVar[n]; for (int i = 0; i < n; ++i) { - ends[i] = tasks [i] - .EndExpr() - .Var(); + ends[i] = tasks[i].EndExpr().Var(); } IntVar end_time = ends.Max().VarWithName("end_time"); @@ -118,10 +113,7 @@ public class FurnitureMovingIntervals { while (solver.NextSolution()) { Console.WriteLine(num_workers.ToString() + ", " + end_time.ToString()); for (int i = 0; i < n; i++) { - Console.WriteLine("{0} (demand:{1})", - tasks [i] - .ToString(), - demand[i]); + Console.WriteLine("{0} (demand:{1})", tasks[i].ToString(), demand[i]); } Console.WriteLine(); } @@ -134,5 +126,7 @@ public class FurnitureMovingIntervals { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/futoshiki.cs b/examples/contrib/futoshiki.cs index 7e8a29b7c0..40b929611e 100644 --- a/examples/contrib/futoshiki.cs +++ b/examples/contrib/futoshiki.cs @@ -38,7 +38,7 @@ public class Futoshiki { * Also see http://www.hakank.org/or-tools/futoshiki.py * */ - private static void Solve(int[, ] values, int[, ] lt) { + private static void Solve(int[,] values, int[,] lt) { Solver solver = new Solver("Futoshiki"); int size = values.GetLength(0); @@ -48,7 +48,7 @@ public class Futoshiki { // // Decision variables // - IntVar[, ] field = solver.MakeIntVarMatrix(size, size, 1, size, "field"); + IntVar[,] field = solver.MakeIntVarMatrix(size, size, 1, size, "field"); IntVar[] field_flat = field.Flatten(); // @@ -66,36 +66,32 @@ public class Futoshiki { // all rows have to be different foreach (int row in RANGE) { - solver.Add( - (from col in RANGE select field[row, col]).ToArray().AllDifferent()); + solver.Add((from col in RANGE select field[row, col]).ToArray().AllDifferent()); } // all columns have to be different foreach (int col in RANGE) { - solver.Add( - (from row in RANGE select field[row, col]).ToArray().AllDifferent()); + solver.Add((from row in RANGE select field[row, col]).ToArray().AllDifferent()); } // all < constraints are satisfied // Also: make 0-based foreach (int i in NUMQD) { - solver.Add(field[lt[i, 0] - 1, lt[i, 1] - 1] < - field[lt[i, 2] - 1, lt[i, 3] - 1]); + solver.Add(field[lt[i, 0] - 1, lt[i, 1] - 1] < field[lt[i, 2] - 1, lt[i, 3] - 1]); } // // Search // - DecisionBuilder db = solver.MakePhase( - field_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(field_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { foreach (int i in RANGE) { foreach (int j in RANGE) { - Console.Write("{0} ", field [i, j] - .Value()); + Console.Write("{0} ", field[i, j].Value()); } Console.WriteLine(); } @@ -124,17 +120,15 @@ public class Futoshiki { // Futoshiki instance, by Andras Salamon // specify the numbers in the grid // - int[, ] values1 = {{0, 0, 3, 2, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}}; + int[,] values1 = { + { 0, 0, 3, 2, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } + }; // [i1,j1, i2,j2] requires that values[i1,j1] < values[i2,j2] // Note: 1-based - int[, ] lt1 = {{1, 2, 1, 1}, {1, 4, 1, 5}, {2, 3, 1, 3}, {3, 3, 2, 3}, - {3, 4, 2, 4}, {2, 5, 3, 5}, {3, 2, 4, 2}, {4, 4, 4, 3}, - {5, 2, 5, 1}, {5, 4, 5, 3}, {5, 5, 4, 5}}; + int[,] lt1 = { { 1, 2, 1, 1 }, { 1, 4, 1, 5 }, { 2, 3, 1, 3 }, { 3, 3, 2, 3 }, + { 3, 4, 2, 4 }, { 2, 5, 3, 5 }, { 3, 2, 4, 2 }, { 4, 4, 4, 3 }, + { 5, 2, 5, 1 }, { 5, 4, 5, 3 }, { 5, 5, 4, 5 } }; // // Example from http://en.wikipedia.org/wiki/Futoshiki @@ -145,15 +139,13 @@ public class Futoshiki { // 3 5 2 1 4 // 1 2 5 4 3 // - int[, ] values2 = {{0, 0, 0, 0, 0}, - {4, 0, 0, 0, 2}, - {0, 0, 4, 0, 0}, - {0, 0, 0, 0, 4}, - {0, 0, 0, 0, 0}}; + int[,] values2 = { + { 0, 0, 0, 0, 0 }, { 4, 0, 0, 0, 2 }, { 0, 0, 4, 0, 0 }, { 0, 0, 0, 0, 4 }, { 0, 0, 0, 0, 0 } + }; // Note: 1-based - int[, ] lt2 = {{1, 2, 1, 1}, {1, 4, 1, 3}, {1, 5, 1, 4}, - {4, 4, 4, 5}, {5, 1, 5, 2}, {5, 2, 5, 3}}; + int[,] lt2 = { { 1, 2, 1, 1 }, { 1, 4, 1, 3 }, { 1, 5, 1, 4 }, + { 4, 4, 4, 5 }, { 5, 1, 5, 2 }, { 5, 2, 5, 3 } }; Console.WriteLine("Problem 1"); Solve(values1, lt1); diff --git a/examples/contrib/golomb_ruler.cs b/examples/contrib/golomb_ruler.cs index 0a5f6903de..533c6097fd 100644 --- a/examples/contrib/golomb_ruler.cs +++ b/examples/contrib/golomb_ruler.cs @@ -35,8 +35,7 @@ public class GolombRuler { // // Decision variables // - IntVar[] ticks = solver.MakeIntVarArray( - m, 0, ((m < 31) ? (1 << (m + 1)) - 1 : 9999), "ticks"); + IntVar[] ticks = solver.MakeIntVarArray(m, 0, ((m < 31) ? (1 << (m + 1)) - 1 : 9999), "ticks"); IntVar[] diff = new IntVar[(m * m - m) / 2]; @@ -66,14 +65,13 @@ public class GolombRuler { // // Optimization // - OptimizeVar opt = ticks [m - 1] - .Minimize(1); + OptimizeVar opt = ticks[m - 1].Minimize(1); // // Search // - DecisionBuilder db = solver.MakePhase( - ticks, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(ticks, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); // We just want the debug info for larger instances. if (m >= 11) { @@ -85,11 +83,9 @@ public class GolombRuler { } while (solver.NextSolution()) { - Console.Write("opt: {0} [ ", ticks [m - 1] - .Value()); + Console.Write("opt: {0} [ ", ticks[m - 1].Value()); for (int i = 0; i < m; i++) { - Console.Write("{0} ", ticks [i] - .Value()); + Console.Write("{0} ", ticks[i].Value()); } Console.WriteLine("]"); } diff --git a/examples/contrib/grocery.cs b/examples/contrib/grocery.cs index 293100e79b..7f77ee6916 100644 --- a/examples/contrib/grocery.cs +++ b/examples/contrib/grocery.cs @@ -79,15 +79,13 @@ public class Grocery { // // Search // - DecisionBuilder db = solver.MakePhase(item, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(item, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write(item [i] - .Value() + - " "); + Console.Write(item[i].Value() + " "); } Console.WriteLine(); } @@ -99,5 +97,7 @@ public class Grocery { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/hidato_table.cs b/examples/contrib/hidato_table.cs index f56267090c..9c392975d6 100644 --- a/examples/contrib/hidato_table.cs +++ b/examples/contrib/hidato_table.cs @@ -33,7 +33,7 @@ public class HidatoTable { * cols: the number of columns in the grid */ public static IntTupleSet BuildPairs(int rows, int cols) { - int[] ix = {-1, 0, 1}; + int[] ix = { -1, 0, 1 }; var result_tmp = (from x in Enumerable.Range(0, rows) from y in Enumerable.Range(0, cols) from dx in ix from dy in ix where x + @@ -78,7 +78,7 @@ public class HidatoTable { // models, a 0 indicates an open cell which number is not yet known. // - int[, ] puzzle = null; + int[,] puzzle = null; if (model == 1) { // Simple problem @@ -86,50 +86,48 @@ public class HidatoTable { // 6 7 9 // 5 2 8 // 1 4 3 - int[, ] puzzle1 = {{6, 0, 9}, {0, 2, 8}, {1, 0, 0}}; + int[,] puzzle1 = { { 6, 0, 9 }, { 0, 2, 8 }, { 1, 0, 0 } }; puzzle = puzzle1; } else if (model == 2) { - int[, ] puzzle2 = {{0, 44, 41, 0, 0, 0, 0}, {0, 43, 0, 28, 29, 0, 0}, - {0, 1, 0, 0, 0, 33, 0}, {0, 2, 25, 4, 34, 0, 36}, - {49, 16, 0, 23, 0, 0, 0}, {0, 19, 0, 0, 12, 7, 0}, - {0, 0, 0, 14, 0, 0, 0}}; + int[,] puzzle2 = { { 0, 44, 41, 0, 0, 0, 0 }, { 0, 43, 0, 28, 29, 0, 0 }, + { 0, 1, 0, 0, 0, 33, 0 }, { 0, 2, 25, 4, 34, 0, 36 }, + { 49, 16, 0, 23, 0, 0, 0 }, { 0, 19, 0, 0, 12, 7, 0 }, + { 0, 0, 0, 14, 0, 0, 0 } }; puzzle = puzzle2; } else if (model == 3) { // Problems from the book: // Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles" // Problem 1 (Practice) - int[, ] puzzle3 = {{0, 0, 20, 0, 0}, - {0, 0, 0, 16, 18}, - {22, 0, 15, 0, 0}, - {23, 0, 1, 14, 11}, - {0, 25, 0, 0, 12}}; + int[,] puzzle3 = { { 0, 0, 20, 0, 0 }, + { 0, 0, 0, 16, 18 }, + { 22, 0, 15, 0, 0 }, + { 23, 0, 1, 14, 11 }, + { 0, 25, 0, 0, 12 } }; puzzle = puzzle3; } else if (model == 4) { // problem 2 (Practice) - int[, ] puzzle4 = {{0, 0, 0, 0, 14}, - {0, 18, 12, 0, 0}, - {0, 0, 17, 4, 5}, - {0, 0, 7, 0, 0}, - {9, 8, 25, 1, 0}}; + int[,] puzzle4 = { { 0, 0, 0, 0, 14 }, + { 0, 18, 12, 0, 0 }, + { 0, 0, 17, 4, 5 }, + { 0, 0, 7, 0, 0 }, + { 9, 8, 25, 1, 0 } }; puzzle = puzzle4; } else if (model == 5) { // problem 3 (Beginner) - int[, ] puzzle5 = {{0, 26, 0, 0, 0, 18}, {0, 0, 27, 0, 0, 19}, - {31, 23, 0, 0, 14, 0}, {0, 33, 8, 0, 15, 1}, - {0, 0, 0, 5, 0, 0}, {35, 36, 0, 10, 0, 0}}; + int[,] puzzle5 = { { 0, 26, 0, 0, 0, 18 }, { 0, 0, 27, 0, 0, 19 }, { 31, 23, 0, 0, 14, 0 }, + { 0, 33, 8, 0, 15, 1 }, { 0, 0, 0, 5, 0, 0 }, { 35, 36, 0, 10, 0, 0 } }; puzzle = puzzle5; } else if (model == 6) { // Problem 15 (Intermediate) - int[, ] puzzle6 = { - {64, 0, 0, 0, 0, 0, 0, 0}, {1, 63, 0, 59, 15, 57, 53, 0}, - {0, 4, 0, 14, 0, 0, 0, 0}, {3, 0, 11, 0, 20, 19, 0, 50}, - {0, 0, 0, 0, 22, 0, 48, 40}, {9, 0, 0, 32, 23, 0, 0, 41}, - {27, 0, 0, 0, 36, 0, 46, 0}, {28, 30, 0, 35, 0, 0, 0, 0}}; + int[,] puzzle6 = { { 64, 0, 0, 0, 0, 0, 0, 0 }, { 1, 63, 0, 59, 15, 57, 53, 0 }, + { 0, 4, 0, 14, 0, 0, 0, 0 }, { 3, 0, 11, 0, 20, 19, 0, 50 }, + { 0, 0, 0, 0, 22, 0, 48, 40 }, { 9, 0, 0, 32, 23, 0, 0, 41 }, + { 27, 0, 0, 0, 36, 0, 46, 0 }, { 28, 30, 0, 35, 0, 0, 0, 0 } }; puzzle = puzzle6; } @@ -167,15 +165,15 @@ public class HidatoTable { // We use an allowed assignment constraint to model it. IntTupleSet close_tuples = BuildPairs(r, c); for (int k = 1; k < r * c - 1; k++) { - IntVar[] tmp = new IntVar[]{positions[k], positions[k + 1]}; + IntVar[] tmp = new IntVar[] { positions[k], positions[k + 1] }; solver.Add(tmp.AllowedAssignments(close_tuples)); } // // Search // - DecisionBuilder db = solver.MakePhase( - positions, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(positions, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -194,12 +192,11 @@ public class HidatoTable { } // Print the current solution - public static void PrintOneSolution(IntVar[] positions, int rows, int cols, - int num_solution) { + public static void PrintOneSolution(IntVar[] positions, int rows, int cols, int num_solution) { Console.WriteLine("Solution {0}", num_solution); // Create empty board - int[, ] board = new int[rows, cols]; + int[,] board = new int[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i, j] = 0; @@ -208,8 +205,7 @@ public class HidatoTable { // Fill board with solution value for (int k = 0; k < rows * cols; k++) { - int position = (int) positions [k] - .Value(); + int position = (int)positions[k].Value(); board[position / cols, position % cols] = k + 1; } @@ -217,7 +213,7 @@ public class HidatoTable { } // Pretty print of the matrix - public static void PrintMatrix(int[, ] game) { + public static void PrintMatrix(int[,] game) { int rows = game.GetLength(0); int cols = game.GetLength(1); diff --git a/examples/contrib/just_forgotten.cs b/examples/contrib/just_forgotten.cs index d761512fdf..a56d74ee00 100644 --- a/examples/contrib/just_forgotten.cs +++ b/examples/contrib/just_forgotten.cs @@ -54,10 +54,10 @@ public class JustForgotten { int cols = 10; // The four tries - int[, ] a = {{9, 4, 6, 2, 1, 5, 7, 8, 3, 0}, - {8, 6, 0, 4, 3, 9, 1, 2, 5, 7}, - {1, 6, 4, 0, 2, 9, 7, 8, 5, 3}, - {6, 8, 2, 4, 3, 1, 9, 0, 7, 5}}; + int[,] a = { { 9, 4, 6, 2, 1, 5, 7, 8, 3, 0 }, + { 8, 6, 0, 4, 3, 9, 1, 2, 5, 7 }, + { 1, 6, 4, 0, 2, 9, 7, 8, 5, 3 }, + { 6, 8, 2, 4, 3, 1, 9, 0, 7, 5 } }; // // Decision variables @@ -69,34 +69,27 @@ public class JustForgotten { // solver.Add(x.AllDifferent()); for (int r = 0; r < rows; r++) { - solver.Add((from c in Enumerable.Range(0, cols) select x[c] == a[r, c]) - .ToArray() - .Sum() == 4); + solver.Add((from c in Enumerable.Range(0, cols) select x[c] == a[r, c]).ToArray().Sum() == 4); } // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.WriteLine("Account number:"); for (int j = 0; j < cols; j++) { - Console.Write(x [j] - .Value() + - " "); + Console.Write(x[j].Value() + " "); } Console.WriteLine("\n"); - Console.WriteLine( - "The four tries, where '!' represents a correct digit:"); + Console.WriteLine("The four tries, where '!' represents a correct digit:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { String c = " "; - if (a[i, j] == x [j] - .Value()) { + if (a[i, j] == x[j].Value()) { c = "!"; } Console.Write("{0}{1} ", a[i, j], c); @@ -114,5 +107,7 @@ public class JustForgotten { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/kakuro.cs b/examples/contrib/kakuro.cs index 5459886fd2..cb2f26e290 100644 --- a/examples/contrib/kakuro.cs +++ b/examples/contrib/kakuro.cs @@ -25,7 +25,7 @@ public class Kakuro { * in cc == res * */ - public static void calc(Solver solver, int[] cc, IntVar[, ] x, int res) { + public static void calc(Solver solver, int[] cc, IntVar[,] x, int res) { // ensure that the values are positive int len = cc.Length / 2; for (int i = 0; i < len; i++) { @@ -33,8 +33,7 @@ public class Kakuro { } // sum the numbers - solver.Add((from i in Enumerable.Range(0, len) - select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]) + solver.Add((from i in Enumerable.Range(0, len) select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]) .ToArray() .Sum() == res); } @@ -85,31 +84,31 @@ public class Kakuro { // segments: // sum, the segments // Note: this is 1-based - int[][] problem = {new int[]{16, 1, 1, 1, 2}, - new int[]{24, 1, 5, 1, 6, 1, 7}, - new int[]{17, 2, 1, 2, 2}, - new int[]{29, 2, 4, 2, 5, 2, 6, 2, 7}, - new int[]{35, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5}, - new int[]{7, 4, 2, 4, 3}, - new int[]{8, 4, 5, 4, 6}, - new int[]{16, 5, 3, 5, 4, 5, 5, 5, 6, 5, 7}, - new int[]{21, 6, 1, 6, 2, 6, 3, 6, 4}, - new int[]{5, 6, 6, 6, 7}, - new int[]{6, 7, 1, 7, 2, 7, 3}, - new int[]{3, 7, 6, 7, 7}, + int[][] problem = { new int[] { 16, 1, 1, 1, 2 }, + new int[] { 24, 1, 5, 1, 6, 1, 7 }, + new int[] { 17, 2, 1, 2, 2 }, + new int[] { 29, 2, 4, 2, 5, 2, 6, 2, 7 }, + new int[] { 35, 3, 1, 3, 2, 3, 3, 3, 4, 3, 5 }, + new int[] { 7, 4, 2, 4, 3 }, + new int[] { 8, 4, 5, 4, 6 }, + new int[] { 16, 5, 3, 5, 4, 5, 5, 5, 6, 5, 7 }, + new int[] { 21, 6, 1, 6, 2, 6, 3, 6, 4 }, + new int[] { 5, 6, 6, 6, 7 }, + new int[] { 6, 7, 1, 7, 2, 7, 3 }, + new int[] { 3, 7, 6, 7, 7 }, - new int[]{23, 1, 1, 2, 1, 3, 1}, - new int[]{30, 1, 2, 2, 2, 3, 2, 4, 2}, - new int[]{27, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5}, - new int[]{12, 1, 6, 2, 6}, - new int[]{16, 1, 7, 2, 7}, - new int[]{17, 2, 4, 3, 4}, - new int[]{15, 3, 3, 4, 3, 5, 3, 6, 3, 7, 3}, - new int[]{12, 4, 6, 5, 6, 6, 6, 7, 6}, - new int[]{7, 5, 4, 6, 4}, - new int[]{7, 5, 7, 6, 7, 7, 7}, - new int[]{11, 6, 1, 7, 1}, - new int[]{10, 6, 2, 7, 2} + new int[] { 23, 1, 1, 2, 1, 3, 1 }, + new int[] { 30, 1, 2, 2, 2, 3, 2, 4, 2 }, + new int[] { 27, 1, 5, 2, 5, 3, 5, 4, 5, 5, 5 }, + new int[] { 12, 1, 6, 2, 6 }, + new int[] { 16, 1, 7, 2, 7 }, + new int[] { 17, 2, 4, 3, 4 }, + new int[] { 15, 3, 3, 4, 3, 5, 3, 6, 3, 7, 3 }, + new int[] { 12, 4, 6, 5, 6, 6, 6, 7, 6 }, + new int[] { 7, 5, 4, 6, 4 }, + new int[] { 7, 5, 7, 6, 7, 7, 7 }, + new int[] { 11, 6, 1, 7, 1 }, + new int[] { 10, 6, 2, 7, 2 } }; @@ -117,15 +116,15 @@ public class Kakuro { // The blanks // Note: 1-based - int[, ] blanks = {{1, 3}, {1, 4}, {2, 3}, {3, 6}, {3, 7}, {4, 1}, {4, 4}, - {4, 7}, {5, 1}, {5, 2}, {6, 5}, {7, 4}, {7, 5}}; + int[,] blanks = { { 1, 3 }, { 1, 4 }, { 2, 3 }, { 3, 6 }, { 3, 7 }, { 4, 1 }, { 4, 4 }, + { 4, 7 }, { 5, 1 }, { 5, 2 }, { 6, 5 }, { 7, 4 }, { 7, 5 } }; int num_blanks = blanks.GetLength(0); // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 0, 9, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, 9, "x"); IntVar[] x_flat = x.Flatten(); // @@ -151,8 +150,7 @@ public class Kakuro { // all numbers in this segment must be distinct int len = segment.Length / 2; - solver.Add((from j in Enumerable.Range(0, len) - select x[s2[j * 2] - 1, s2[j * 2 + 1] - 1]) + solver.Add((from j in Enumerable.Range(0, len) select x[s2[j * 2] - 1, s2[j * 2 + 1] - 1]) .ToArray() .AllDifferent()); } @@ -160,16 +158,15 @@ public class Kakuro { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - int v = (int) x [i, j] - .Value(); + int v = (int)x[i, j].Value(); if (v > 0) { Console.Write(v + " "); } else { @@ -188,5 +185,7 @@ public class Kakuro { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/kenken2.cs b/examples/contrib/kenken2.cs index d5507ab6ab..e89141db0e 100644 --- a/examples/contrib/kenken2.cs +++ b/examples/contrib/kenken2.cs @@ -25,7 +25,7 @@ public class KenKen2 { * in cc == res * */ - public static void calc(Solver solver, int[] cc, IntVar[, ] x, int res) { + public static void calc(Solver solver, int[] cc, IntVar[,] x, int res) { int ccLen = cc.Length; if (ccLen == 4) { // for two operands there's @@ -48,9 +48,8 @@ public class KenKen2 { // sum the numbers int len = cc.Length / 2; - IntVar[] xx = (from i in Enumerable.Range(0, len) - select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]) - .ToArray(); + IntVar[] xx = + (from i in Enumerable.Range(0, len) select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]).ToArray(); // Sum IntVar this_sum = xx.Sum() == res; @@ -59,11 +58,11 @@ public class KenKen2 { // IntVar this_prod = (xx.Prod() == res).Var(); // don't work IntVar this_prod; if (xx.Length == 3) { - this_prod = (x[cc[0] - 1, cc[1] - 1] * x[cc[2] - 1, cc[3] - 1] * - x[cc[4] - 1, cc[5] - 1]) == res; + this_prod = + (x[cc[0] - 1, cc[1] - 1] * x[cc[2] - 1, cc[3] - 1] * x[cc[4] - 1, cc[5] - 1]) == res; } else { - this_prod = (x[cc[0] - 1, cc[1] - 1] * x[cc[2] - 1, cc[3] - 1] * - x[cc[4] - 1, cc[5] - 1] * x[cc[6] - 1, cc[7] - 1]) == res; + this_prod = (x[cc[0] - 1, cc[1] - 1] * x[cc[2] - 1, cc[3] - 1] * x[cc[4] - 1, cc[5] - 1] * + x[cc[6] - 1, cc[7] - 1]) == res; } solver.Add(this_sum + this_prod >= 1); @@ -126,28 +125,28 @@ public class KenKen2 { // hints // sum, the hints // Note: this is 1-based - int[][] problem = {new int[]{11, 1, 1, 2, 1}, - new int[]{2, 1, 2, 1, 3}, - new int[]{20, 1, 4, 2, 4}, - new int[]{6, 1, 5, 1, 6, 2, 6, 3, 6}, - new int[]{3, 2, 2, 2, 3}, - new int[]{3, 2, 5, 3, 5}, - new int[]{240, 3, 1, 3, 2, 4, 1, 4, 2}, - new int[]{6, 3, 3, 3, 4}, - new int[]{6, 4, 3, 5, 3}, - new int[]{7, 4, 4, 5, 4, 5, 5}, - new int[]{30, 4, 5, 4, 6}, - new int[]{6, 5, 1, 5, 2}, - new int[]{9, 5, 6, 6, 6}, - new int[]{8, 6, 1, 6, 2, 6, 3}, - new int[]{2, 6, 4, 6, 5}}; + int[][] problem = { new int[] { 11, 1, 1, 2, 1 }, + new int[] { 2, 1, 2, 1, 3 }, + new int[] { 20, 1, 4, 2, 4 }, + new int[] { 6, 1, 5, 1, 6, 2, 6, 3, 6 }, + new int[] { 3, 2, 2, 2, 3 }, + new int[] { 3, 2, 5, 3, 5 }, + new int[] { 240, 3, 1, 3, 2, 4, 1, 4, 2 }, + new int[] { 6, 3, 3, 3, 4 }, + new int[] { 6, 4, 3, 5, 3 }, + new int[] { 7, 4, 4, 5, 4, 5, 5 }, + new int[] { 30, 4, 5, 4, 6 }, + new int[] { 6, 5, 1, 5, 2 }, + new int[] { 9, 5, 6, 6, 6 }, + new int[] { 8, 6, 1, 6, 2, 6, 3 }, + new int[] { 2, 6, 4, 6, 5 } }; int num_p = problem.GetLength(0); // Number of segments // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); IntVar[] x_flat = x.Flatten(); // @@ -180,17 +179,14 @@ public class KenKen2 { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } @@ -205,5 +201,7 @@ public class KenKen2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/killer_sudoku.cs b/examples/contrib/killer_sudoku.cs index 6feb8edb11..2d7b123991 100644 --- a/examples/contrib/killer_sudoku.cs +++ b/examples/contrib/killer_sudoku.cs @@ -25,11 +25,10 @@ public class KillerSudoku { * in cc == res * */ - public static void calc(Solver solver, int[] cc, IntVar[, ] x, int res) { + public static void calc(Solver solver, int[] cc, IntVar[,] x, int res) { // sum the numbers int len = cc.Length / 2; - solver.Add((from i in Enumerable.Range(0, len) - select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]) + solver.Add((from i in Enumerable.Range(0, len) select x[cc[i * 2] - 1, cc[i * 2 + 1] - 1]) .ToArray() .Sum() == res); } @@ -96,35 +95,35 @@ public class KillerSudoku { // hints // sum, the hints // Note: this is 1-based - int[][] problem = {new int[]{3, 1, 1, 1, 2}, - new int[]{15, 1, 3, 1, 4, 1, 5}, - new int[]{22, 1, 6, 2, 5, 2, 6, 3, 5}, - new int[]{4, 1, 7, 2, 7}, - new int[]{16, 1, 8, 2, 8}, - new int[]{15, 1, 9, 2, 9, 3, 9, 4, 9}, - new int[]{25, 2, 1, 2, 2, 3, 1, 3, 2}, - new int[]{17, 2, 3, 2, 4}, - new int[]{9, 3, 3, 3, 4, 4, 4}, - new int[]{8, 3, 6, 4, 6, 5, 6}, - new int[]{20, 3, 7, 3, 8, 4, 7}, - new int[]{6, 4, 1, 5, 1}, - new int[]{14, 4, 2, 4, 3}, - new int[]{17, 4, 5, 5, 5, 6, 5}, - new int[]{17, 4, 8, 5, 7, 5, 8}, - new int[]{13, 5, 2, 5, 3, 6, 2}, - new int[]{20, 5, 4, 6, 4, 7, 4}, - new int[]{12, 5, 9, 6, 9}, - new int[]{27, 6, 1, 7, 1, 8, 1, 9, 1}, - new int[]{6, 6, 3, 7, 2, 7, 3}, - new int[]{20, 6, 6, 7, 6, 7, 7}, - new int[]{6, 6, 7, 6, 8}, - new int[]{10, 7, 5, 8, 4, 8, 5, 9, 4}, - new int[]{14, 7, 8, 7, 9, 8, 8, 8, 9}, - new int[]{8, 8, 2, 9, 2}, - new int[]{16, 8, 3, 9, 3}, - new int[]{15, 8, 6, 8, 7}, - new int[]{13, 9, 5, 9, 6, 9, 7}, - new int[]{17, 9, 8, 9, 9} + int[][] problem = { new int[] { 3, 1, 1, 1, 2 }, + new int[] { 15, 1, 3, 1, 4, 1, 5 }, + new int[] { 22, 1, 6, 2, 5, 2, 6, 3, 5 }, + new int[] { 4, 1, 7, 2, 7 }, + new int[] { 16, 1, 8, 2, 8 }, + new int[] { 15, 1, 9, 2, 9, 3, 9, 4, 9 }, + new int[] { 25, 2, 1, 2, 2, 3, 1, 3, 2 }, + new int[] { 17, 2, 3, 2, 4 }, + new int[] { 9, 3, 3, 3, 4, 4, 4 }, + new int[] { 8, 3, 6, 4, 6, 5, 6 }, + new int[] { 20, 3, 7, 3, 8, 4, 7 }, + new int[] { 6, 4, 1, 5, 1 }, + new int[] { 14, 4, 2, 4, 3 }, + new int[] { 17, 4, 5, 5, 5, 6, 5 }, + new int[] { 17, 4, 8, 5, 7, 5, 8 }, + new int[] { 13, 5, 2, 5, 3, 6, 2 }, + new int[] { 20, 5, 4, 6, 4, 7, 4 }, + new int[] { 12, 5, 9, 6, 9 }, + new int[] { 27, 6, 1, 7, 1, 8, 1, 9, 1 }, + new int[] { 6, 6, 3, 7, 2, 7, 3 }, + new int[] { 20, 6, 6, 7, 6, 7, 7 }, + new int[] { 6, 6, 7, 6, 8 }, + new int[] { 10, 7, 5, 8, 4, 8, 5, 9, 4 }, + new int[] { 14, 7, 8, 7, 9, 8, 8, 8, 9 }, + new int[] { 8, 8, 2, 9, 2 }, + new int[] { 16, 8, 3, 9, 3 }, + new int[] { 15, 8, 6, 8, 7 }, + new int[] { 13, 9, 5, 9, 6, 9, 7 }, + new int[] { 17, 9, 8, 9, 9 } }; @@ -133,7 +132,7 @@ public class KillerSudoku { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 0, 9, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, 9, "x"); IntVar[] x_flat = x.Flatten(); // @@ -155,10 +154,10 @@ public class KillerSudoku { // cells foreach (int i in CELL) { foreach (int j in CELL) { - solver.Add((from di in CELL from dj in CELL select - x[i * cell_size + di, j * cell_size + dj]) - .ToArray() - .AllDifferent()); + solver.Add( + (from di in CELL from dj in CELL select x[i * cell_size + di, j * cell_size + dj]) + .ToArray() + .AllDifferent()); } } @@ -177,8 +176,7 @@ public class KillerSudoku { // all numbers in this segment must be distinct int len = segment.Length / 2; - solver.Add((from j in Enumerable.Range(0, len) - select x[s2[j * 2] - 1, s2[j * 2 + 1] - 1]) + solver.Add((from j in Enumerable.Range(0, len) select x[s2[j * 2] - 1, s2[j * 2 + 1] - 1]) .ToArray() .AllDifferent()); } @@ -186,16 +184,14 @@ public class KillerSudoku { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - int v = (int) x [i, j] - .Value(); + int v = (int)x[i, j].Value(); if (v > 0) { Console.Write(v + " "); } else { @@ -214,5 +210,7 @@ public class KillerSudoku { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/labeled_dice.cs b/examples/contrib/labeled_dice.cs index a900a82b8d..1db9cd2913 100644 --- a/examples/contrib/labeled_dice.cs +++ b/examples/contrib/labeled_dice.cs @@ -80,15 +80,13 @@ public class LabeledDice { int W = 22; int Y = 23; - String[] letters_str = {"A", "B", "C", "D", "E", "F", "G", "H", - "I", "J", "K", "L", "M", "N", "O", "P", - "Q", "R", "S", "T", "U", "V", "W", "Y"}; + String[] letters_str = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", + "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y" }; int num_words = 13; - int[, ] words = {{B, U, O, Y}, {C, A, V, E}, {C, E, L, T}, {F, L, U, B}, - {F, O, R, K}, {H, E, M, P}, {J, U, D, Y}, {J, U, N, K}, - {L, I, M, N}, {Q, U, I, P}, {S, W, A, G}, {V, I, S, A}, - {W, I, S, H}}; + int[,] words = { { B, U, O, Y }, { C, A, V, E }, { C, E, L, T }, { F, L, U, B }, { F, O, R, K }, + { H, E, M, P }, { J, U, D, Y }, { J, U, N, K }, { L, I, M, N }, { Q, U, I, P }, + { S, W, A, G }, { V, I, S, A }, { W, I, S, H } }; // // Decision variables @@ -102,9 +100,8 @@ public class LabeledDice { // the letters in a word must be on a different die for (int i = 0; i < num_words; i++) { - solver.Add((from j in Enumerable.Range(0, n) select dice[words[i, j]]) - .ToArray() - .AllDifferent()); + solver.Add( + (from j in Enumerable.Range(0, n) select dice[words[i, j]]).ToArray().AllDifferent()); } // there must be exactly 6 letters of each die @@ -121,8 +118,8 @@ public class LabeledDice { // // Search // - DecisionBuilder db = solver.MakePhase(dice, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(dice, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -130,8 +127,7 @@ public class LabeledDice { for (int d = 0; d < n; d++) { Console.Write("die {0}: ", d); for (int i = 0; i < m; i++) { - if (dice [i] - .Value() == d) { + if (dice[i].Value() == d) { Console.Write(letters_str[i]); } } @@ -141,8 +137,7 @@ public class LabeledDice { Console.WriteLine("The words with the cube label:"); for (int i = 0; i < num_words; i++) { for (int j = 0; j < n; j++) { - Console.Write("{0} ({1})", letters_str[words[i, j]], - dice[words[i, j]].Value()); + Console.Write("{0} ({1})", letters_str[words[i, j]], dice[words[i, j]].Value()); } Console.WriteLine(); } @@ -157,5 +152,7 @@ public class LabeledDice { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/langford.cs b/examples/contrib/langford.cs index cf8c10bfa0..a8740f7c6e 100644 --- a/examples/contrib/langford.cs +++ b/examples/contrib/langford.cs @@ -48,9 +48,7 @@ public class Langford { solver.Add(position.AllDifferent()); for (int i = 1; i <= k; i++) { - solver.Add(position[i + k - 1] - - (position[i - 1] + solver.MakeIntVar(i + 1, i + 1)) == - 0); + solver.Add(position[i + k - 1] - (position[i - 1] + solver.MakeIntVar(i + 1, i + 1)) == 0); solver.Add(solution.Element(position[i - 1]) == i); solver.Add(solution.Element(position[k + i - 1]) == i); } @@ -61,8 +59,8 @@ public class Langford { // // Search // - DecisionBuilder db = solver.MakePhase(position, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(position, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -70,9 +68,7 @@ public class Langford { while (solver.NextSolution()) { Console.Write("solution : "); for (int i = 0; i < p; i++) { - Console.Write(solution [i] - .Value() + - " "); + Console.Write(solution[i].Value() + " "); } Console.WriteLine(); num_solutions++; diff --git a/examples/contrib/least_diff.cs b/examples/contrib/least_diff.cs index 571a172b75..0743c94bae 100644 --- a/examples/contrib/least_diff.cs +++ b/examples/contrib/least_diff.cs @@ -40,10 +40,10 @@ public class LeastDiff { IntVar I = solver.MakeIntVar(0, 9, "I"); IntVar J = solver.MakeIntVar(0, 9, "J"); - IntVar[] all = new IntVar[]{A, B, C, D, E, F, G, H, I, J}; - int[] coeffs = {10000, 1000, 100, 10, 1}; - IntVar x = new IntVar[]{A, B, C, D, E}.ScalProd(coeffs).Var(); - IntVar y = new IntVar[]{F, G, H, I, J}.ScalProd(coeffs).Var(); + IntVar[] all = new IntVar[] { A, B, C, D, E, F, G, H, I, J }; + int[] coeffs = { 10000, 1000, 100, 10, 1 }; + IntVar x = new IntVar[] { A, B, C, D, E }.ScalProd(coeffs).Var(); + IntVar y = new IntVar[] { F, G, H, I, J }.ScalProd(coeffs).Var(); IntVar diff = (x - y).VarWithName("diff"); // @@ -62,13 +62,12 @@ public class LeastDiff { // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(all, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { - Console.WriteLine("{0} - {1} = {2} ({3}", x.Value(), y.Value(), - diff.Value(), diff.ToString()); + Console.WriteLine("{0} - {1} = {2} ({3}", x.Value(), y.Value(), diff.Value(), + diff.ToString()); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); @@ -79,5 +78,7 @@ public class LeastDiff { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/lectures.cs b/examples/contrib/lectures.cs index 95c9e57fc6..3cc86f6788 100644 --- a/examples/contrib/lectures.cs +++ b/examples/contrib/lectures.cs @@ -52,7 +52,7 @@ public class Lectures { // The schedule requirements: // lecture a cannot be held at the same time as b // Note: 1-based (compensated in the constraints). - int[, ] g = {{1, 2}, {1, 4}, {3, 5}, {2, 6}, {4, 5}, {5, 6}, {1, 6}}; + int[,] g = { { 1, 2 }, { 1, 4 }, { 3, 5 }, { 2, 6 }, { 4, 5 }, { 5, 6 }, { 1, 6 } }; // number of nodes int n = 6; @@ -97,21 +97,18 @@ public class Lectures { // // Search // - DecisionBuilder db = solver.MakePhase(v, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(v, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("\nmax hours: {0}", max_c.Value() + 1); - Console.WriteLine("v: " + String.Join(" ", (from i in Enumerable - .Range(0, n) select v [i] - .Value()) - .ToArray())); + Console.WriteLine( + "v: " + + String.Join(" ", (from i in Enumerable.Range(0, n) select v[i].Value()).ToArray())); for (int i = 0; i < n; i++) { - Console.WriteLine("Lecture {0} at {1}h", i, - v [i] - .Value()); + Console.WriteLine("Lecture {0} at {1}h", i, v[i].Value()); } Console.WriteLine("\n"); } @@ -125,12 +122,11 @@ public class Lectures { } // Print the current solution - public static void PrintOneSolution(IntVar[] positions, int rows, int cols, - int num_solution) { + public static void PrintOneSolution(IntVar[] positions, int rows, int cols, int num_solution) { Console.WriteLine("Solution {0}", num_solution); // Create empty board - int[, ] board = new int[rows, cols]; + int[,] board = new int[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i, j] = 0; @@ -139,8 +135,7 @@ public class Lectures { // Fill board with solution value for (int k = 0; k < rows * cols; k++) { - int position = (int) positions [k] - .Value(); + int position = (int)positions[k].Value(); board[position / cols, position % cols] = k + 1; } @@ -148,7 +143,7 @@ public class Lectures { } // Pretty print of the matrix - public static void PrintMatrix(int[, ] game) { + public static void PrintMatrix(int[,] game) { int rows = game.GetLength(0); int cols = game.GetLength(1); @@ -165,5 +160,7 @@ public class Lectures { Console.WriteLine(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/magic_sequence.cs b/examples/contrib/magic_sequence.cs index 08d204d3a0..ccb3f5630f 100644 --- a/examples/contrib/magic_sequence.cs +++ b/examples/contrib/magic_sequence.cs @@ -62,16 +62,14 @@ public class MagicSequence { // // Search // - DecisionBuilder db = solver.MakePhase(all_vars, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(all_vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < size; i++) { - Console.Write(all_vars [i] - .Value() + - " "); + Console.Write(all_vars[i].Value() + " "); } Console.WriteLine(); } @@ -91,7 +89,7 @@ public class MagicSequence { } else { // Let's test some diferent sizes - foreach (int i in new int[]{2, 10, 100, 200, 500}) { + foreach (int i in new int[] { 2, 10, 100, 200, 500 }) { Solve(i); } } diff --git a/examples/contrib/magic_square.cs b/examples/contrib/magic_square.cs index 9b67c4bd71..43c9db8061 100644 --- a/examples/contrib/magic_square.cs +++ b/examples/contrib/magic_square.cs @@ -31,7 +31,7 @@ public class MagicSquare { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, n * n, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n * n, "x"); // for the branching IntVar[] x_flat = x.Flatten(); @@ -78,8 +78,8 @@ public class MagicSquare { // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); @@ -88,9 +88,7 @@ public class MagicSquare { if (print != 0) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/magic_square_and_cards.cs b/examples/contrib/magic_square_and_cards.cs index f291b7e96c..bc820212cd 100644 --- a/examples/contrib/magic_square_and_cards.cs +++ b/examples/contrib/magic_square_and_cards.cs @@ -42,7 +42,7 @@ public class MagicSquareAndCards { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, 13, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, 13, "x"); IntVar[] x_flat = x.Flatten(); IntVar s = solver.MakeIntVar(1, 13 * 4, "s"); @@ -78,8 +78,8 @@ public class MagicSquareAndCards { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); @@ -87,16 +87,12 @@ public class MagicSquareAndCards { Console.WriteLine("s: {0}", s.Value()); Console.Write("counts:"); for (int i = 0; i < 14; i++) { - Console.Write(counts [i] - .Value() + - " "); + Console.Write(counts[i].Value() + " "); } Console.WriteLine(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/map.cs b/examples/contrib/map.cs index a1a162c386..23b3217dff 100644 --- a/examples/contrib/map.cs +++ b/examples/contrib/map.cs @@ -64,15 +64,14 @@ public class Map { // // Search // - DecisionBuilder db = solver.MakePhase( - color, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(color, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("colors: "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", color [i] - .Value()); + Console.Write("{0} ", color[i].Value()); } Console.WriteLine(); @@ -86,5 +85,7 @@ public class Map { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/map2.cs b/examples/contrib/map2.cs index 61776c087b..dc8fa28c3f 100644 --- a/examples/contrib/map2.cs +++ b/examples/contrib/map2.cs @@ -44,10 +44,11 @@ public class Map2 { int n = 6; int max_num_colors = 4; - int[, ] neighbours = { - {France, Belgium}, {France, Luxembourg}, {France, Germany}, - {Luxembourg, Germany}, {Luxembourg, Belgium}, {Belgium, Netherlands}, - {Belgium, Germany}, {Germany, Netherlands}, {Germany, Denmark}}; + int[,] neighbours = { { France, Belgium }, { France, Luxembourg }, + { France, Germany }, { Luxembourg, Germany }, + { Luxembourg, Belgium }, { Belgium, Netherlands }, + { Belgium, Germany }, { Germany, Netherlands }, + { Germany, Denmark } }; // // Decision variables @@ -67,15 +68,14 @@ public class Map2 { // // Search // - DecisionBuilder db = solver.MakePhase( - color, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(color, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("colors: "); for (int i = 0; i < n; i++) { - Console.Write("{0} ", color [i] - .Value()); + Console.Write("{0} ", color[i].Value()); } Console.WriteLine(); @@ -89,5 +89,7 @@ public class Map2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/marathon2.cs b/examples/contrib/marathon2.cs index 54a45c0a05..5b50e55ca6 100644 --- a/examples/contrib/marathon2.cs +++ b/examples/contrib/marathon2.cs @@ -51,8 +51,7 @@ public class Marathon2 { // Data // int n = 6; - String[] runners_str = {"Dominique", "Ignace", "Naren", - "Olivier", "Philippe", "Pascal"}; + String[] runners_str = { "Dominique", "Ignace", "Naren", "Olivier", "Philippe", "Pascal" }; // // Decision variables @@ -101,8 +100,8 @@ public class Marathon2 { // // Search // - DecisionBuilder db = solver.MakePhase( - runners, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(runners, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); @@ -110,8 +109,7 @@ public class Marathon2 { int[] runners_val = new int[n]; Console.Write("runners: "); for (int i = 0; i < n; i++) { - runners_val[i] = (int) runners [i] - .Value(); + runners_val[i] = (int)runners[i].Value(); Console.Write(runners_val[i] + " "); } Console.WriteLine("\nPlaces:"); @@ -132,5 +130,7 @@ public class Marathon2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/max_flow_taha.cs b/examples/contrib/max_flow_taha.cs index 4f45754e63..db1af7b531 100644 --- a/examples/contrib/max_flow_taha.cs +++ b/examples/contrib/max_flow_taha.cs @@ -45,16 +45,16 @@ public class MaxFlowTaha { IEnumerable NODES = Enumerable.Range(0, n); // cost matrix - int[, ] c = {{0, 20, 30, 10, 0}, - {0, 0, 40, 0, 30}, - {0, 0, 0, 10, 20}, - {0, 0, 5, 0, 20}, - {0, 0, 0, 0, 0}}; + int[,] c = { { 0, 20, 30, 10, 0 }, + { 0, 0, 40, 0, 30 }, + { 0, 0, 0, 10, 20 }, + { 0, 0, 5, 0, 20 }, + { 0, 0, 0, 0, 0 } }; // // Decision variables // - IntVar[, ] x = new IntVar[n, n]; + IntVar[,] x = new IntVar[n, n]; foreach (int i in NODES) { foreach (int j in NODES) { x[i, j] = solver.MakeIntVar(0, c[i, j], "x"); @@ -111,30 +111,24 @@ public class MaxFlowTaha { // // Search // - DecisionBuilder db = - solver.MakePhase(x_flat.Concat(in_flow).Concat(out_flow).ToArray(), - Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = solver.MakePhase(x_flat.Concat(in_flow).Concat(out_flow).ToArray(), + Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("total: {0}", total.Value()); Console.Write("in_flow : "); foreach (int i in NODES) { - Console.Write(in_flow [i] - .Value() + - " "); + Console.Write(in_flow[i].Value() + " "); } Console.Write("\nout_flow: "); foreach (int i in NODES) { - Console.Write(out_flow [i] - .Value() + - " "); + Console.Write(out_flow[i].Value() + " "); } Console.WriteLine(); foreach (int i in NODES) { foreach (int j in NODES) { - Console.Write("{0,2} ", x [i, j] - .Value()); + Console.Write("{0,2} ", x[i, j].Value()); } Console.WriteLine(); } @@ -149,5 +143,7 @@ public class MaxFlowTaha { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/max_flow_winston1.cs b/examples/contrib/max_flow_winston1.cs index efc5edd3df..643e224d6f 100644 --- a/examples/contrib/max_flow_winston1.cs +++ b/examples/contrib/max_flow_winston1.cs @@ -44,15 +44,15 @@ public class MaxFlowWinston1 { // Note: // This is 1-based to be compatible with other implementations. // - int[, ] arcs1 = {{1, 2}, {1, 3}, {2, 3}, {2, 4}, {3, 5}, {4, 5}, {5, 1}}; + int[,] arcs1 = { { 1, 2 }, { 1, 3 }, { 2, 3 }, { 2, 4 }, { 3, 5 }, { 4, 5 }, { 5, 1 } }; // Capacities - int[] cap = {2, 3, 3, 4, 2, 1, 100}; + int[] cap = { 2, 3, 3, 4, 2, 1, 100 }; // Convert arcs to 0-based int num_arcs = arcs1.GetLength(0); IEnumerable ARCS = Enumerable.Range(0, num_arcs); - int[, ] arcs = new int[num_arcs, 2]; + int[,] arcs = new int[num_arcs, 2]; foreach (int i in ARCS) { for (int j = 0; j < 2; j++) { arcs[i, j] = arcs1[i, j] - 1; @@ -60,7 +60,7 @@ public class MaxFlowWinston1 { } // Convert arcs to matrix (for sanity checking below) - int[, ] mat = new int[num_arcs, num_arcs]; + int[,] mat = new int[num_arcs, num_arcs]; foreach (int i in NODES) { foreach (int j in NODES) { int c = 0; @@ -76,9 +76,8 @@ public class MaxFlowWinston1 { // // Decision variables // - IntVar[, ] flow = solver.MakeIntVarMatrix(n, n, 0, 200, "flow"); - IntVar z = flow [n - 1, 0] - .VarWithName("z"); + IntVar[,] flow = solver.MakeIntVarMatrix(n, n, 0, 200, "flow"); + IntVar z = flow[n - 1, 0].VarWithName("z"); // // Constraints @@ -121,17 +120,15 @@ public class MaxFlowWinston1 { // // Search // - DecisionBuilder db = solver.MakePhase( - flow.Flatten(), Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(flow.Flatten(), Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("z: {0}", z.Value()); foreach (int i in NODES) { foreach (int j in NODES) { - Console.Write(flow [i, j] - .Value() + - " "); + Console.Write(flow[i, j].Value() + " "); } Console.WriteLine(); } @@ -146,5 +143,7 @@ public class MaxFlowWinston1 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/minesweeper.cs b/examples/contrib/minesweeper.cs index d931c0c0da..b569f6c05a 100644 --- a/examples/contrib/minesweeper.cs +++ b/examples/contrib/minesweeper.cs @@ -29,16 +29,15 @@ public class Minesweeper { // static int default_r = 8; static int default_c = 8; - static int[, ] default_game = { - {2, 3, X, 2, 2, X, 2, 1}, {X, X, 4, X, X, 4, X, 2}, - {X, X, X, X, X, X, 4, X}, {X, 5, X, 6, X, X, X, 2}, - {2, X, X, X, 5, 5, X, 2}, {1, 3, 4, X, X, X, 4, X}, - {0, 1, X, 4, X, X, X, 3}, {0, 1, 2, X, 2, 3, X, 2}}; + static int[,] default_game = { { 2, 3, X, 2, 2, X, 2, 1 }, { X, X, 4, X, X, 4, X, 2 }, + { X, X, X, X, X, X, 4, X }, { X, 5, X, 6, X, X, X, 2 }, + { 2, X, X, X, 5, 5, X, 2 }, { 1, 3, 4, X, X, X, 4, X }, + { 0, 1, X, 4, X, X, X, 3 }, { 0, 1, 2, X, 2, 3, X, 2 } }; // for the actual problem static int r; static int c; - static int[, ] game; + static int[,] game; /** * @@ -53,7 +52,7 @@ public class Minesweeper { // // data // - int[] S = {-1, 0, 1}; + int[] S = { -1, 0, 1 }; Console.WriteLine("Problem:"); for (int i = 0; i < r; i++) { @@ -71,7 +70,7 @@ public class Minesweeper { // // Decision variables // - IntVar[, ] mines = solver.MakeIntVarMatrix(r, c, 0, 1, "mines"); + IntVar[,] mines = solver.MakeIntVarMatrix(r, c, 0, 1, "mines"); // for branching IntVar[] mines_flat = mines.Flatten(); @@ -84,8 +83,10 @@ public class Minesweeper { solver.Add(mines[i, j] == 0); // this cell is the sum of all its neighbours - var tmp = from a in S from b in S where i + a >= 0 && j + b >= 0 && - i + a < r && j + b < c select(mines[i + a, j + b]); + var tmp = from a in S from b in S + where i + + a >= 0 && j + b >= 0 && + i + a dice[(d + 1) % m, r2])) - .ToArray() - .Sum() - .Var(); + IntVar sum1 = (from r1 in Enumerable.Range(0, n) from r2 in Enumerable.Range(0, n) + select(dice[d % m, r1] > dice[(d + 1) % m, r2])) + .ToArray() + .Sum() + .Var(); solver.Add(comp[d % m, 0] == sum1); - IntVar sum2 = - (from r1 in Enumerable.Range(0, n) from r2 in Enumerable.Range(0, n) - select(dice[(d + 1) % m, r1] > dice[d % m, r2])) - .ToArray() - .Sum() - .Var(); + IntVar sum2 = (from r1 in Enumerable.Range(0, n) from r2 in Enumerable.Range(0, n) + select(dice[(d + 1) % m, r1] > dice[d % m, r2])) + .ToArray() + .Sum() + .Var(); solver.Add(comp[d % m, 1] == sum2); } @@ -122,8 +120,7 @@ public class NonTransitiveDice { // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.ASSIGN_MIN_VALUE); if (minimize_val > 0) { Console.WriteLine("Minimizing max_val"); @@ -142,35 +139,28 @@ public class NonTransitiveDice { while (solver.NextSolution()) { Console.WriteLine("gap_sum: {0}", gap_sum.Value()); - Console.WriteLine("gap: {0}", (from i in Enumerable - .Range(0, m) select gap [i] - .Value() - .ToString()) - .ToArray()); + Console.WriteLine( + "gap: {0}", + (from i in Enumerable.Range(0, m) select gap[i].Value().ToString()).ToArray()); Console.WriteLine("max_val: {0}", max_val.Value()); Console.WriteLine("max_win: {0}", max_win.Value()); Console.WriteLine("dice:"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { - Console.Write(dice [i, j] - .Value() + - " "); + Console.Write(dice[i, j].Value() + " "); } Console.WriteLine(); } Console.WriteLine("comp:"); for (int i = 0; i < m; i++) { for (int j = 0; j < 2; j++) { - Console.Write(comp [i, j] - .Value() + - " "); + Console.Write(comp[i, j].Value() + " "); } Console.WriteLine(); } Console.WriteLine("counts:"); for (int i = 1; i < n * 2 + 1; i++) { - int c = (int) counts [i] - .Value(); + int c = (int)counts[i].Value(); if (c > 0) { Console.Write("{0}({1}) ", i, c); } diff --git a/examples/contrib/nqueens.cs b/examples/contrib/nqueens.cs index f7f9ac9de9..0068e78468 100644 --- a/examples/contrib/nqueens.cs +++ b/examples/contrib/nqueens.cs @@ -63,16 +63,15 @@ public class NQueens { // // Search // - DecisionBuilder db = solver.MakePhase(q, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, - Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(q, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db); int c = 0; while (solver.NextSolution()) { if (print > 0) { for (int i = 0; i < n; i++) { - Console.Write("{0} ", q [i] - .Value()); + Console.Write("{0} ", q[i].Value()); } Console.WriteLine(); diff --git a/examples/contrib/nurse_rostering_regular.cs b/examples/contrib/nurse_rostering_regular.cs index 4683877794..d19f33b8d4 100644 --- a/examples/contrib/nurse_rostering_regular.cs +++ b/examples/contrib/nurse_rostering_regular.cs @@ -43,8 +43,7 @@ public class NurseRostering { * F : accepting states * */ - static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[, ] d, - int q0, int[] F) { + static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[,] d, int q0, int[] F) { Debug.Assert(Q > 0, "regular: 'Q' must be greater than zero"); Debug.Assert(S > 0, "regular: 'S' must be greater than zero"); @@ -52,8 +51,7 @@ public class NurseRostering { // each possible input; each extra transition is from state zero // to state zero. This allows us to continue even if we hit a // non-accepted input. - int[][] d2 = new int [Q + 1] - []; + int[][] d2 = new int [Q + 1][]; for (int i = 0; i <= Q; i++) { int[] row = new int[S]; for (int j = 0; j < S; j++) { @@ -67,9 +65,7 @@ public class NurseRostering { } int[] d2_flatten = - (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) - select d2 [i] - [j]) + (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) select d2[i][j]) .ToArray(); // If x has index set m..n, then a[m-1] holds the initial state @@ -81,8 +77,7 @@ public class NurseRostering { IntVar[] a = solver.MakeIntVarArray(n + 1 - m, 0, Q + 1, "a"); // Check that the final state is in F - solver.Add(a [a.Length - 1] - .Member(F)); + solver.Add(a[a.Length - 1].Member(F)); // First state is q0 solver.Add(a[m] == q0); @@ -126,43 +121,41 @@ public class NurseRostering { int day_shift = 1; int night_shift = 2; int off_shift = 3; - int[] shifts = {dummy_shift, day_shift, night_shift, off_shift}; - int[] valid_shifts = {day_shift, night_shift, off_shift}; + int[] shifts = { dummy_shift, day_shift, night_shift, off_shift }; + int[] valid_shifts = { day_shift, night_shift, off_shift }; // the DFA (for regular) int n_states = 6; int input_max = 3; int initial_state = 1; // 0 is for the failing state - int[] accepting_states = {1, 2, 3, 4, 5, 6}; + int[] accepting_states = { 1, 2, 3, 4, 5, 6 }; - int[, ] transition_fn = { - // d,n,o - {2, 3, 1}, // state 1 - {4, 4, 1}, // state 2 - {4, 5, 1}, // state 3 - {6, 6, 1}, // state 4 - {6, 0, 1}, // state 5 - {0, 0, 1} // state 6 + int[,] transition_fn = { + // d,n,o + { 2, 3, 1 }, // state 1 + { 4, 4, 1 }, // state 2 + { 4, 5, 1 }, // state 3 + { 6, 6, 1 }, // state 4 + { 6, 0, 1 }, // state 5 + { 0, 0, 1 } // state 6 }; - string[] days = {"d", "n", "o"}; // for presentation + string[] days = { "d", "n", "o" }; // for presentation // // Decision variables // // For regular - IntVar[, ] x = - solver.MakeIntVarMatrix(num_nurses, num_days, valid_shifts, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(num_nurses, num_days, valid_shifts, "x"); IntVar[] x_flat = x.Flatten(); // summary of the nurses - IntVar[] nurse_stat = - solver.MakeIntVarArray(num_nurses, 0, num_days, "nurse_stat"); + IntVar[] nurse_stat = solver.MakeIntVarArray(num_nurses, 0, num_days, "nurse_stat"); // summary of the shifts per day int num_shifts = shifts.Length; - IntVar[, ] day_stat = new IntVar[num_days, num_shifts]; + IntVar[,] day_stat = new IntVar[num_days, num_shifts]; for (int i = 0; i < num_days; i++) { for (int j = 0; j < num_shifts; j++) { day_stat[i, j] = solver.MakeIntVar(0, num_nurses, "day_stat"); @@ -177,8 +170,8 @@ public class NurseRostering { for (int j = 0; j < num_days; j++) { reg_input[j] = x[i, j]; } - MyRegular(solver, reg_input, n_states, input_max, transition_fn, - initial_state, accepting_states); + MyRegular(solver, reg_input, n_states, input_max, transition_fn, initial_state, + accepting_states); } // @@ -238,8 +231,8 @@ public class NurseRostering { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -250,9 +243,7 @@ public class NurseRostering { Console.Write("Nurse #{0,-2}: ", i); var occ = new Dictionary(); for (int j = 0; j < num_days; j++) { - int v = (int) x [i, j] - .Value() - - 1; + int v = (int)x[i, j].Value() - 1; if (!occ.ContainsKey(v)) { occ[v] = 0; } @@ -260,8 +251,7 @@ public class NurseRostering { Console.Write(days[v] + " "); } - Console.Write(" #workdays: {0,2}", nurse_stat [i] - .Value()); + Console.Write(" #workdays: {0,2}", nurse_stat[i].Value()); foreach (int s in valid_shifts) { int v = 0; if (occ.ContainsKey(s - 1)) { @@ -277,9 +267,7 @@ public class NurseRostering { for (int j = 0; j < num_days; j++) { Console.Write("Day #{0,2}: ", j); foreach (int t in valid_shifts) { - Console.Write(day_stat [j, t] - .Value() + - " "); + Console.Write(day_stat[j, t].Value() + " "); } Console.WriteLine(); } @@ -299,5 +287,7 @@ public class NurseRostering { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/nurse_rostering_transition.cs b/examples/contrib/nurse_rostering_transition.cs index 0457d95dcc..c19198b481 100644 --- a/examples/contrib/nurse_rostering_transition.cs +++ b/examples/contrib/nurse_rostering_transition.cs @@ -60,12 +60,12 @@ public class NurseRostering { int day_shift = 1; int night_shift = 2; int off_shift = 3; - int[] shifts = {dummy_shift, day_shift, night_shift, off_shift}; - int[] valid_shifts = {day_shift, night_shift, off_shift}; + int[] shifts = { dummy_shift, day_shift, night_shift, off_shift }; + int[] valid_shifts = { day_shift, night_shift, off_shift }; // the DFA (for regular) int initial_state = 1; - int[] accepting_states = {1, 2, 3, 4, 5, 6}; + int[] accepting_states = { 1, 2, 3, 4, 5, 6 }; /* // This is the transition function @@ -84,14 +84,14 @@ public class NurseRostering { // For TransitionConstraint IntTupleSet transition_tuples = new IntTupleSet(3); // state, input, next state - transition_tuples.InsertAll(new long[][]{ - new long[]{1, 1, 2}, new long[]{1, 2, 3}, new long[]{1, 3, 1}, - new long[]{2, 1, 4}, new long[]{2, 2, 4}, new long[]{2, 3, 1}, - new long[]{3, 1, 4}, new long[]{3, 2, 5}, new long[]{3, 3, 1}, - new long[]{4, 1, 6}, new long[]{4, 2, 6}, new long[]{4, 3, 1}, - new long[]{5, 1, 6}, new long[]{5, 3, 1}, new long[]{6, 3, 1}}); + transition_tuples.InsertAll( + new long[][] { new long[] { 1, 1, 2 }, new long[] { 1, 2, 3 }, new long[] { 1, 3, 1 }, + new long[] { 2, 1, 4 }, new long[] { 2, 2, 4 }, new long[] { 2, 3, 1 }, + new long[] { 3, 1, 4 }, new long[] { 3, 2, 5 }, new long[] { 3, 3, 1 }, + new long[] { 4, 1, 6 }, new long[] { 4, 2, 6 }, new long[] { 4, 3, 1 }, + new long[] { 5, 1, 6 }, new long[] { 5, 3, 1 }, new long[] { 6, 3, 1 } }); - string[] days = {"d", "n", "o"}; // for presentation + string[] days = { "d", "n", "o" }; // for presentation // // Decision variables @@ -100,8 +100,7 @@ public class NurseRostering { // // For TransitionConstraint // - IntVar[, ] x = - solver.MakeIntVarMatrix(num_nurses, num_days, valid_shifts, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(num_nurses, num_days, valid_shifts, "x"); IntVar[] x_flat = x.Flatten(); // @@ -113,7 +112,7 @@ public class NurseRostering { // summary of the shifts per day // int num_shifts = shifts.Length; - IntVar[, ] day_stat = new IntVar[num_days, num_shifts]; + IntVar[,] day_stat = new IntVar[num_days, num_shifts]; for (int i = 0; i < num_days; i++) { for (int j = 0; j < num_shifts; j++) { day_stat[i, j] = solver.MakeIntVar(0, num_nurses, "day_stat"); @@ -129,8 +128,7 @@ public class NurseRostering { reg_input[j] = x[i, j]; } - solver.Add(reg_input.Transition(transition_tuples, initial_state, - accepting_states)); + solver.Add(reg_input.Transition(transition_tuples, initial_state, accepting_states)); } // @@ -140,8 +138,7 @@ public class NurseRostering { // Number of worked days (either day or night shift) IntVar[] nurse_days = new IntVar[num_days]; for (int day = 0; day < num_days; day++) { - nurse_days[day] = x [nurse, day] - .IsMember(new int[]{day_shift, night_shift}); + nurse_days[day] = x[nurse, day].IsMember(new int[] { day_shift, night_shift }); } nurse_stat[nurse] = nurse_days.Sum().Var(); @@ -193,8 +190,8 @@ public class NurseRostering { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); SearchMonitor log = solver.MakeSearchLog(1000000); @@ -207,9 +204,7 @@ public class NurseRostering { Console.Write("Nurse #{0,-2}: ", i); var occ = new Dictionary(); for (int j = 0; j < num_days; j++) { - int v = (int) x [i, j] - .Value() - - 1; + int v = (int)x[i, j].Value() - 1; if (!occ.ContainsKey(v)) { occ[v] = 0; } @@ -217,8 +212,7 @@ public class NurseRostering { Console.Write(days[v] + " "); } - Console.Write(" #workdays: {0,2}", nurse_stat [i] - .Value()); + Console.Write(" #workdays: {0,2}", nurse_stat[i].Value()); foreach (int s in valid_shifts) { int v = 0; if (occ.ContainsKey(s - 1)) { @@ -234,9 +228,7 @@ public class NurseRostering { for (int j = 0; j < num_days; j++) { Console.Write("Day #{0,2}: ", j); foreach (int t in valid_shifts) { - Console.Write(day_stat [j, t] - .Value() + - " "); + Console.Write(day_stat[j, t].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/olympic.cs b/examples/contrib/olympic.cs index 61f54fec98..461f87a331 100644 --- a/examples/contrib/olympic.cs +++ b/examples/contrib/olympic.cs @@ -97,15 +97,13 @@ public class Olympic { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write("{0,2} ", x [i] - .Value()); + Console.Write("{0,2} ", x[i].Value()); } Console.WriteLine(); } @@ -118,5 +116,7 @@ public class Olympic { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/organize_day.cs b/examples/contrib/organize_day.cs index 2a9a353311..b889014da1 100644 --- a/examples/contrib/organize_day.cs +++ b/examples/contrib/organize_day.cs @@ -24,8 +24,7 @@ public class OrganizeDay { // // No overlapping of tasks s1 and s2 // - public static void NoOverlap(Solver solver, IntVar s1, int d1, IntVar s2, - int d2) { + public static void NoOverlap(Solver solver, IntVar s1, int d1, IntVar s2, int d2) { solver.Add((s1 + d1 <= s2) + (s2 + d2 <= s1) == 1); } @@ -53,11 +52,11 @@ public class OrganizeDay { int mail = 1; int shop = 2; int bank = 3; - int[] tasks = {work, mail, shop, bank}; - int[] durations = {4, 1, 2, 1}; + int[] tasks = { work, mail, shop, bank }; + int[] durations = { 4, 1, 2, 1 }; // task [i,0] must be finished before task [i,1] - int[, ] before_tasks = {{bank, shop}, {mail, work}}; + int[,] before_tasks = { { bank, shop }, { mail, work } }; // the valid times of the day int begin = 9; @@ -94,19 +93,14 @@ public class OrganizeDay { // // Search // - DecisionBuilder db = solver.MakePhase(begins, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(begins, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { foreach (int t in tasks) { - Console.WriteLine("Task {0}: {1,2} .. ({2}) .. {3,2}", t, - begins [t] - .Value(), - durations[t], - ends [t] - .Value()); + Console.WriteLine("Task {0}: {1,2} .. ({2}) .. {3,2}", t, begins[t].Value(), durations[t], + ends[t].Value()); } Console.WriteLine(); } @@ -119,5 +113,7 @@ public class OrganizeDay { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/organize_day_intervals.cs b/examples/contrib/organize_day_intervals.cs index a498bfcf24..d23d3bf655 100644 --- a/examples/contrib/organize_day_intervals.cs +++ b/examples/contrib/organize_day_intervals.cs @@ -47,21 +47,21 @@ public class OrganizeDay { int begin = 9; int end = 17; // tasks - int[] tasks = {work, mail, shop, bank}; + int[] tasks = { work, mail, shop, bank }; // durations - int[] durations = {4, 1, 2, 1}; + int[] durations = { 4, 1, 2, 1 }; // Arrays for interval variables. - int[] starts_max = {begin, begin, begin, begin}; - int[] ends_max = {end - 4, end - 1, end - 2, end - 1}; + int[] starts_max = { begin, begin, begin, begin }; + int[] ends_max = { end - 4, end - 1, end - 2, end - 1 }; // task [i,0] must be finished before task [i,1] - int[, ] before_tasks = {{bank, shop}, {mail, work}}; + int[,] before_tasks = { { bank, shop }, { mail, work } }; // // Decision variables // - IntervalVar[] intervals = solver.MakeFixedDurationIntervalVarArray( - n, starts_max, ends_max, durations, false, "task"); + IntervalVar[] intervals = + solver.MakeFixedDurationIntervalVarArray(n, starts_max, ends_max, durations, false, "task"); // // Constraints // @@ -72,26 +72,23 @@ public class OrganizeDay { for (int t = 0; t < before_tasks.GetLength(0); t++) { int before = before_tasks[t, 0]; int after = before_tasks[t, 1]; - solver.Add(intervals [after] - .StartsAfterEnd(intervals[before])); + solver.Add(intervals[after].StartsAfterEnd(intervals[before])); } - solver.Add(intervals [work] - .StartsAfter(11)); + solver.Add(intervals[work].StartsAfter(11)); // // Search // SequenceVar var = disjunctive.SequenceVar(); - SequenceVar[] seq_array = new SequenceVar[]{var}; + SequenceVar[] seq_array = new SequenceVar[] { var }; DecisionBuilder db = solver.MakePhase(seq_array, Solver.SEQUENCE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { foreach (int t in tasks) { - Console.WriteLine(intervals [t] - .ToString()); + Console.WriteLine(intervals[t].ToString()); } Console.WriteLine(); } @@ -104,5 +101,7 @@ public class OrganizeDay { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/p_median.cs b/examples/contrib/p_median.cs index 06de8c3737..9f3e19adf8 100644 --- a/examples/contrib/p_median.cs +++ b/examples/contrib/p_median.cs @@ -50,27 +50,25 @@ public class PMedian { int num_warehouses = 3; IEnumerable WAREHOUSES = Enumerable.Range(0, num_warehouses); - int[] demand = {100, 80, 80, 70}; - int[, ] distance = {{2, 10, 50}, {2, 10, 52}, {50, 60, 3}, {40, 60, 1}}; + int[] demand = { 100, 80, 80, 70 }; + int[,] distance = { { 2, 10, 50 }, { 2, 10, 52 }, { 50, 60, 3 }, { 40, 60, 1 } }; // // Decision variables // - IntVar[] open = - solver.MakeIntVarArray(num_warehouses, 0, num_warehouses, "open"); - IntVar[, ] ship = - solver.MakeIntVarMatrix(num_customers, num_warehouses, 0, 1, "ship"); + IntVar[] open = solver.MakeIntVarArray(num_warehouses, 0, num_warehouses, "open"); + IntVar[,] ship = solver.MakeIntVarMatrix(num_customers, num_warehouses, 0, 1, "ship"); IntVar z = solver.MakeIntVar(0, 1000, "z"); // // Constraints // - solver.Add((from c in CUSTOMERS from w in WAREHOUSES select( - demand[c] * distance[c, w] * ship[c, w])) - .ToArray() - .Sum() == z); + solver.Add( + (from c in CUSTOMERS from w in WAREHOUSES select(demand[c] * distance[c, w] * ship[c, w])) + .ToArray() + .Sum() == z); solver.Add(open.Sum() == p); @@ -90,9 +88,8 @@ public class PMedian { // // Search // - DecisionBuilder db = - solver.MakePhase(open.Concat(ship.Flatten()).ToArray(), - Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(open.Concat(ship.Flatten()).ToArray(), + Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); @@ -100,16 +97,12 @@ public class PMedian { Console.WriteLine("z: {0}", z.Value()); Console.Write("open:"); foreach (int w in WAREHOUSES) { - Console.Write(open [w] - .Value() + - " "); + Console.Write(open[w].Value() + " "); } Console.WriteLine(); foreach (int c in CUSTOMERS) { foreach (int w in WAREHOUSES) { - Console.Write(ship [c, w] - .Value() + - " "); + Console.Write(ship[c, w].Value() + " "); } Console.WriteLine(); } @@ -124,5 +117,7 @@ public class PMedian { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/pandigital_numbers.cs b/examples/contrib/pandigital_numbers.cs index b26b5c5ced..fe65750dc5 100644 --- a/examples/contrib/pandigital_numbers.cs +++ b/examples/contrib/pandigital_numbers.cs @@ -31,7 +31,7 @@ public class PandigitalNumbers { int len = a.Length; IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { - tmp[i] = (a[i] * (int) Math.Pow(bbase, len - i - 1)).Var(); + tmp[i] = (a[i] * (int)Math.Pow(bbase, len - i - 1)).Var(); } return tmp.Sum() == num; } @@ -75,8 +75,7 @@ public class PandigitalNumbers { * Also see http://www.hakank.org/or-tools/pandigital_numbers.py * */ - private static void Solve(int bbase = 10, int start = 1, int len1 = 1, - int len2 = 4) { + private static void Solve(int bbase = 10, int start = 1, int len1 = 1, int len2 = 4) { Solver solver = new Solver("PandigitalNumbers"); // @@ -84,7 +83,7 @@ public class PandigitalNumbers { // int max_d = bbase - 1; int x_len = max_d + 1 - start; - int max_num = (int) Math.Pow(bbase, 4) - 1; + int max_num = (int)Math.Pow(bbase, 4) - 1; // // Decision variables @@ -109,18 +108,13 @@ public class PandigitalNumbers { // solver.Add(x.AllDifferent()); - solver.Add( - ToNum((from i in Enumerable.Range(0, len1) select x[i]).ToArray(), num1, - bbase)); + solver.Add(ToNum((from i in Enumerable.Range(0, len1) select x[i]).ToArray(), num1, bbase)); - solver.Add( - ToNum((from i in Enumerable.Range(len1, len2) select x[i]).ToArray(), - num2, bbase)); + solver.Add(ToNum((from i in Enumerable.Range(len1, len2) select x[i]).ToArray(), num2, bbase)); - solver.Add(ToNum((from i in Enumerable.Range( - len1 + len2, x_len - (len1 + len2)) select x[i]) - .ToArray(), - res, bbase)); + solver.Add(ToNum( + (from i in Enumerable.Range(len1 + len2, x_len - (len1 + len2)) select x[i]).ToArray(), res, + bbase)); solver.Add(num1 * num2 == res); @@ -135,14 +129,12 @@ public class PandigitalNumbers { // // Search // - DecisionBuilder db = - solver.MakePhase(all, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { - Console.WriteLine("{0} * {1} = {2}", num1.Value(), num2.Value(), - res.Value()); + Console.WriteLine("{0} * {1} = {2}", num1.Value(), num2.Value(), res.Value()); } /* diff --git a/examples/contrib/partition.cs b/examples/contrib/partition.cs index 15b4849463..645c39fc73 100644 --- a/examples/contrib/partition.cs +++ b/examples/contrib/partition.cs @@ -71,13 +71,9 @@ public class Partition { sx = new IntVar[m]; sy = new IntVar[m]; for (int i = m - 1; i >= 0; i--) { - sx[i] = x [i] - .Square() - .Var(); + sx[i] = x[i].Square().Var(); sxy[i] = sx[i]; - sy[i] = y [i] - .Square() - .Var(); + sy[i] = y[i].Square().Var(); sxy[m + i] = sy[i]; } solver.Add(sxy.ScalProd(coeffs) == 0); @@ -97,17 +93,11 @@ public class Partition { while (solver.NextSolution()) { for (int i = 0; i < m; i++) { - Console.Write("[" + - xy [i] - .Value() + - "] "); + Console.Write("[" + xy[i].Value() + "] "); } Console.WriteLine(); for (int i = 0; i < m; i++) { - Console.Write("[" + - xy [m + i] - .Value() + - "] "); + Console.Write("[" + xy[m + i].Value() + "] "); } Console.WriteLine("\n"); } diff --git a/examples/contrib/perfect_square_sequence.cs b/examples/contrib/perfect_square_sequence.cs index 91544fec9e..f69d6b58aa 100644 --- a/examples/contrib/perfect_square_sequence.cs +++ b/examples/contrib/perfect_square_sequence.cs @@ -50,8 +50,7 @@ public class PerfectSquareSequence { * Also see http://www.hakank.org/or-tools/perfect_square_sequence.py * */ - private static int Solve(int n = 15, int print_solutions = 1, - int show_num_sols = 0) { + private static int Solve(int n = 15, int print_solutions = 1, int show_num_sols = 0) { Solver solver = new Solver("PerfectSquareSequence"); IEnumerable RANGE = Enumerable.Range(0, n); @@ -83,8 +82,7 @@ public class PerfectSquareSequence { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); @@ -94,9 +92,7 @@ public class PerfectSquareSequence { if (print_solutions > 0) { Console.Write("x: "); foreach (int i in RANGE) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } diff --git a/examples/contrib/photo_problem.cs b/examples/contrib/photo_problem.cs index 91b049842a..810edb9089 100644 --- a/examples/contrib/photo_problem.cs +++ b/examples/contrib/photo_problem.cs @@ -54,21 +54,20 @@ public class PhotoProblem { // // Data // - String[] persons = {"Betty", "Chris", "Donald", "Fred", - "Gary", "Mary", "Paul"}; + String[] persons = { "Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul" }; int n = persons.Length; IEnumerable RANGE = Enumerable.Range(0, n); - int[, ] preferences = { - // 0 1 2 3 4 5 6 - // B C D F G M P - {0, 0, 0, 0, 1, 1, 0}, // Betty 0 - {1, 0, 0, 0, 1, 0, 0}, // Chris 1 - {0, 0, 0, 0, 0, 0, 0}, // Donald 2 - {0, 0, 1, 0, 0, 1, 0}, // Fred 3 - {0, 0, 0, 0, 0, 0, 0}, // Gary 4 - {0, 0, 0, 0, 0, 0, 0}, // Mary 5 - {0, 0, 1, 1, 0, 0, 0} // Paul 6 + int[,] preferences = { + // 0 1 2 3 4 5 6 + // B C D F G M P + { 0, 0, 0, 0, 1, 1, 0 }, // Betty 0 + { 1, 0, 0, 0, 1, 0, 0 }, // Chris 1 + { 0, 0, 0, 0, 0, 0, 0 }, // Donald 2 + { 0, 0, 1, 0, 0, 1, 0 }, // Fred 3 + { 0, 0, 0, 0, 0, 0, 0 }, // Gary 4 + { 0, 0, 0, 0, 0, 0, 0 }, // Mary 5 + { 0, 0, 1, 1, 0, 0, 0 } // Paul 6 }; Console.WriteLine("Preferences:"); @@ -113,8 +112,8 @@ public class PhotoProblem { // // Search // - DecisionBuilder db = solver.MakePhase( - positions, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(positions, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); @@ -123,8 +122,7 @@ public class PhotoProblem { int[] p = new int[n]; Console.Write("p: "); for (int i = 0; i < n; i++) { - p[i] = (int) positions [i] - .Value(); + p[i] = (int)positions[i].Value(); Console.Write(p[i] + " "); } Console.WriteLine(); diff --git a/examples/contrib/place_number_puzzle.cs b/examples/contrib/place_number_puzzle.cs index 98263ee29e..f908f2c770 100644 --- a/examples/contrib/place_number_puzzle.cs +++ b/examples/contrib/place_number_puzzle.cs @@ -51,11 +51,11 @@ public class PlaceNumberPuzzle { int n = 8; // Note: this is 1-based for compatibility (and lazyness) - int[, ] graph = {{1, 2}, {1, 3}, {1, 4}, {2, 1}, {2, 3}, {2, 5}, {2, 6}, - {3, 2}, {3, 4}, {3, 6}, {3, 7}, {4, 1}, {4, 3}, {4, 6}, - {4, 7}, {5, 2}, {5, 3}, {5, 6}, {5, 8}, {6, 2}, {6, 3}, - {6, 4}, {6, 5}, {6, 7}, {6, 8}, {7, 3}, {7, 4}, {7, 6}, - {7, 8}, {8, 5}, {8, 6}, {8, 7}}; + int[,] graph = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 1 }, { 2, 3 }, { 2, 5 }, { 2, 6 }, + { 3, 2 }, { 3, 4 }, { 3, 6 }, { 3, 7 }, { 4, 1 }, { 4, 3 }, { 4, 6 }, + { 4, 7 }, { 5, 2 }, { 5, 3 }, { 5, 6 }, { 5, 8 }, { 6, 2 }, { 6, 3 }, + { 6, 4 }, { 6, 5 }, { 6, 7 }, { 6, 8 }, { 7, 3 }, { 7, 4 }, { 7, 6 }, + { 7, 8 }, { 8, 5 }, { 8, 6 }, { 8, 7 } }; // // Decision variables @@ -77,17 +77,14 @@ public class PlaceNumberPuzzle { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -100,5 +97,7 @@ public class PlaceNumberPuzzle { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/post_office_problem2.cs b/examples/contrib/post_office_problem2.cs index d00a52539d..772fab1b43 100644 --- a/examples/contrib/post_office_problem2.cs +++ b/examples/contrib/post_office_problem2.cs @@ -64,13 +64,13 @@ public class PostOfficeProblem2 { // days 0..6, monday 0 int n = 7; - int[] need = {17, 13, 15, 19, 14, 16, 11}; + int[] need = { 17, 13, 15, 19, 14, 16, 11 }; // Total cost for the 5 day schedule. // Base cost per day is 100. // Working saturday is 100 extra // Working sunday is 200 extra. - int[] cost = {500, 600, 800, 800, 800, 800, 700}; + int[] cost = { 500, 600, 800, 800, 800, 800, 700 }; // // Decision variables @@ -107,8 +107,8 @@ public class PostOfficeProblem2 { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db, obj); @@ -117,9 +117,7 @@ public class PostOfficeProblem2 { Console.WriteLine("total_cost: {0}", total_cost.Value()); Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine("\n"); } @@ -132,5 +130,7 @@ public class PostOfficeProblem2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/quasigroup_completion.cs b/examples/contrib/quasigroup_completion.cs index c2fffa7de2..7625fbd013 100644 --- a/examples/contrib/quasigroup_completion.cs +++ b/examples/contrib/quasigroup_completion.cs @@ -36,15 +36,13 @@ public class QuasigroupCompletion { * 3 2 5 4 1 */ static int default_n = 5; - static int[, ] default_problem = {{1, X, X, X, 4}, - {X, 5, X, X, X}, - {4, X, X, 2, X}, - {X, 4, X, X, X}, - {X, X, 5, X, 1}}; + static int[,] default_problem = { + { 1, X, X, X, 4 }, { X, 5, X, X, X }, { 4, X, X, 2, X }, { X, 4, X, X, X }, { X, X, 5, X, 1 } + }; // for the actual problem static int n; - static int[, ] problem; + static int[,] problem; /** * @@ -70,7 +68,7 @@ public class QuasigroupCompletion { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); IntVar[] x_flat = x.Flatten(); // @@ -109,8 +107,7 @@ public class QuasigroupCompletion { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_SIMPLE, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_SIMPLE, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -120,8 +117,7 @@ public class QuasigroupCompletion { Console.WriteLine("Solution #{0} ", sol + " "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write("{0} ", x [i, j] - .Value()); + Console.Write("{0} ", x[i, j].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/regex.cs b/examples/contrib/regex.cs index 63307d964a..a3d41dc8c0 100644 --- a/examples/contrib/regex.cs +++ b/examples/contrib/regex.cs @@ -41,14 +41,12 @@ public class RegexGeneration { * F : accepting states * */ - static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[, ] d, - int q0, int[] F) { + static void MyRegular(Solver solver, IntVar[] x, int Q, int S, int[,] d, int q0, int[] F) { // d2 is the same as d, except we add one extra transition for // each possible input; each extra transition is from state zero // to state zero. This allows us to continue even if we hit a // non-accepted input. - int[][] d2 = new int [Q + 1] - []; + int[][] d2 = new int [Q + 1][]; for (int i = 0; i <= Q; i++) { int[] row = new int[S]; for (int j = 0; j < S; j++) { @@ -62,9 +60,7 @@ public class RegexGeneration { } int[] d2_flatten = - (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) - select d2 [i] - [j]) + (from i in Enumerable.Range(0, Q + 1) from j in Enumerable.Range(0, S) select d2[i][j]) .ToArray(); // If x has index set m..n, then a[m-1] holds the initial state @@ -76,8 +72,7 @@ public class RegexGeneration { IntVar[] a = solver.MakeIntVarArray(n + 1 - m, 0, Q + 1, "a"); // Check that the final state is in F - solver.Add(a [a.Length - 1] - .Member(F)); + solver.Add(a[a.Length - 1].Member(F)); // First state is q0 solver.Add(a[m] == q0); @@ -113,28 +108,27 @@ public class RegexGeneration { int n_states = 11; int input_max = 12; int initial_state = 1; // 0 is for the failing state - int[] accepting_states = {12}; + int[] accepting_states = { 12 }; // The DFA - int[, ] transition_fn = { - // 1 2 3 4 5 6 7 8 9 0 1 2 // - {0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 1 k - {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, // 2 je - {0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0}, // 3 ä - {0, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0}, // 4 ll - {0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0}, // 5 er - {0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0}, // 6 ar - {0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 0, 0}, // 7 st - {0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 0, 0}, // 8 b - {0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0}, // 9 r - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12}, // 10 a - {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12}, // 11 n + int[,] transition_fn = { + // 1 2 3 4 5 6 7 8 9 0 1 2 // + { 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 1 k + { 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0 }, // 2 je + { 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0 }, // 3 ä + { 0, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0 }, // 4 ll + { 0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0 }, // 5 er + { 0, 0, 0, 0, 0, 0, 7, 8, 0, 0, 0, 0 }, // 6 ar + { 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 0, 0 }, // 7 st + { 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 0, 0 }, // 8 b + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0 }, // 9 r + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 12 }, // 10 a + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12 }, // 11 n // 12 d }; // Name of the states - String[] s = {"k", "je", "ä", "ll", "er", "ar", - "st", "b", "r", "a", "n", "d"}; + String[] s = { "k", "je", "ä", "ll", "er", "ar", "st", "b", "r", "a", "n", "d" }; // // Decision variables @@ -144,14 +138,12 @@ public class RegexGeneration { // // Constraints // - MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, - accepting_states); + MyRegular(solver, x, n_states, input_max, transition_fn, initial_state, accepting_states); // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -161,10 +153,7 @@ public class RegexGeneration { // state array (x) so we add it first. res2.Add(s[0]); for (int i = 0; i < n; i++) { - res2.Add(s [x [i] - .Value() - - 1] - ); + res2.Add(s[x[i].Value() - 1]); } res.Add(String.Join("", res2.ToArray())); } diff --git a/examples/contrib/rogo2.cs b/examples/contrib/rogo2.cs index 48be6e249b..2f66c4376d 100644 --- a/examples/contrib/rogo2.cs +++ b/examples/contrib/rogo2.cs @@ -37,11 +37,11 @@ public class Rogo2 { static int default_cols = 9; static int default_max_steps = 12; static int default_best = 8; - static int[, ] default_problem = {{2, W, W, W, W, W, W, W, W}, - {W, 3, W, W, 1, W, W, 2, W}, - {W, W, W, W, W, W, B, W, 2}, - {W, W, 2, B, W, W, W, W, W}, - {W, W, W, W, 2, W, W, 1, W}}; + static int[,] default_problem = { { 2, W, W, W, W, W, W, W, W }, + { W, 3, W, W, 1, W, W, 2, W }, + { W, W, W, W, W, W, B, W, 2 }, + { W, W, 2, B, W, W, W, W, W }, + { W, W, W, W, 2, W, W, 1, W } }; static String default_problem_name = "Problem Mike Trick"; // The actual problem @@ -49,7 +49,7 @@ public class Rogo2 { static int cols; static int max_steps; static int best; - static int[, ] problem; + static int[,] problem; static string problem_name; /** @@ -60,12 +60,11 @@ public class Rogo2 { public static IntTupleSet ValidConnections(int rows, int cols) { IEnumerable ROWS = Enumerable.Range(0, rows); IEnumerable COLS = Enumerable.Range(0, cols); - var result_tmp = - (from i1 in ROWS from j1 in COLS from i2 in ROWS from j2 in COLS where( - Math.Abs(j1 - j2) == 1 && i1 == i2) || - (Math.Abs(i1 - i2) == 1 && j1 % cols == j2 % cols) - select new int[]{i1 * cols + j1, i2 * cols + j2}) - .ToArray(); + var result_tmp = (from i1 in ROWS from j1 in COLS from i2 in ROWS from j2 in COLS where( + Math.Abs(j1 - j2) == 1 && i1 == i2) || + (Math.Abs(i1 - i2) == 1 && j1 % cols == j2 % cols) + select new int[] { i1 * cols + j1, i2 * cols + j2 }) + .ToArray(); // Convert to len x 2 matrix int len = result_tmp.Length; @@ -116,14 +115,12 @@ AllowedAssignments) with the valid connections // int B = -1; - Console.WriteLine("Rows: {0} Cols: {1} Max Steps: {2}", rows, cols, - max_steps); + Console.WriteLine("Rows: {0} Cols: {1} Max Steps: {2}", rows, cols, max_steps); int[] problem_flatten = problem.Cast().ToArray(); int max_point = problem_flatten.Max(); int max_sum = problem_flatten.Sum(); - Console.WriteLine("max_point: {0} max_sum: {1} best: {2}", max_point, - max_sum, best); + Console.WriteLine("max_point: {0} max_sum: {1} best: {2}", max_point, max_sum, best); IEnumerable STEPS = Enumerable.Range(0, max_steps); IEnumerable STEPS1 = Enumerable.Range(0, max_steps - 1); @@ -134,8 +131,7 @@ AllowedAssignments) with the valid connections // // Decision variables // - IntVar[] path = - solver.MakeIntVarArray(max_steps, 0, rows * cols - 1, "path"); + IntVar[] path = solver.MakeIntVarArray(max_steps, 0, rows * cols - 1, "path"); IntVar[] points = solver.MakeIntVarArray(max_steps, 0, best, "points"); IntVar sum_points = points.Sum().VarWithName("sum_points"); @@ -156,12 +152,10 @@ AllowedAssignments) with the valid connections // valid connections foreach (int s in STEPS1) { - solver.Add(new IntVar[]{path[s], path[s + 1]}.AllowedAssignments( - valid_connections)); + solver.Add(new IntVar[] { path[s], path[s + 1] }.AllowedAssignments(valid_connections)); } // around the corner - solver.Add(new IntVar[]{path[max_steps - 1], path[0]}.AllowedAssignments( - valid_connections)); + solver.Add(new IntVar[] { path[max_steps - 1], path[0] }.AllowedAssignments(valid_connections)); // Symmetry breaking for (int s = 1; s < max_steps; s++) { @@ -176,8 +170,7 @@ AllowedAssignments) with the valid connections // // Search // - DecisionBuilder db = solver.MakePhase(path, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(path, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, obj); @@ -185,30 +178,23 @@ AllowedAssignments) with the valid connections Console.WriteLine("sum_points: {0}", sum_points.Value()); Console.Write("path: "); foreach (int s in STEPS) { - Console.Write("{0} ", path [s] - .Value()); + Console.Write("{0} ", path[s].Value()); } Console.WriteLine(); Console.WriteLine("(Adding 1 to coords...)"); - int[, ] sol = new int[rows, cols]; + int[,] sol = new int[rows, cols]; foreach (int s in STEPS) { - int p = (int) path [s] - .Value(); + int p = (int)path[s].Value(); int x = (int)(p / cols); int y = (int)(p % cols); - Console.WriteLine("{0,2},{1,2} ({2} points)", x + 1, y + 1, - points [s] - .Value()); + Console.WriteLine("{0,2},{1,2} ({2} points)", x + 1, y + 1, points[s].Value()); sol[x, y] = 1; } Console.WriteLine("\nThe path is marked by 'X's:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { String p = sol[i, j] == 1 ? "X" : " "; - String q = problem[i, j] == B ? "B" : problem[i, j] == 0 - ? "." - : problem [i, j] - .ToString(); + String q = problem[i, j] == B ? "B" : problem[i, j] == 0 ? "." : problem[i, j].ToString(); Console.Write("{0,2}{1} ", q, p); } Console.WriteLine(); diff --git a/examples/contrib/scheduling_speakers.cs b/examples/contrib/scheduling_speakers.cs index fef901a27e..f4862f1f55 100644 --- a/examples/contrib/scheduling_speakers.cs +++ b/examples/contrib/scheduling_speakers.cs @@ -39,13 +39,13 @@ public class SchedulingSpeakers { // slots available to speak int[][] available = { - // Reasoning: - new int[]{3, 4, 5, 6}, // 2) the only one with 6 after speaker F -> 1 - new int[]{3, 4}, // 5) 3 or 4 - new int[]{2, 3, 4, 5}, // 3) only with 5 after F -> 1 and A -> 6 - new int[]{2, 3, 4}, // 4) only with 2 after C -> 5 and F -> 1 - new int[]{3, 4}, // 5) 3 or 4 - new int[]{1, 2, 3, 4, 5, 6} // 1) the only with 1 + // Reasoning: + new int[] { 3, 4, 5, 6 }, // 2) the only one with 6 after speaker F -> 1 + new int[] { 3, 4 }, // 5) 3 or 4 + new int[] { 2, 3, 4, 5 }, // 3) only with 5 after F -> 1 and A -> 6 + new int[] { 2, 3, 4 }, // 4) only with 2 after C -> 5 and F -> 1 + new int[] { 3, 4 }, // 5) 3 or 4 + new int[] { 1, 2, 3, 4, 5, 6 } // 1) the only with 1 }; // @@ -59,15 +59,13 @@ public class SchedulingSpeakers { solver.Add(x.AllDifferent()); for (int i = 0; i < n; i++) { - solver.Add(x [i] - .Member(available[i])); + solver.Add(x[i].Member(available[i])); } // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -83,5 +81,7 @@ public class SchedulingSpeakers { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/secret_santa.cs b/examples/contrib/secret_santa.cs index 145114c9c3..19a505ce13 100644 --- a/examples/contrib/secret_santa.cs +++ b/examples/contrib/secret_santa.cs @@ -61,7 +61,7 @@ public class SecretSanta { private static void Solve() { Solver solver = new Solver("SecretSanta"); - int[] family = {1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4}; + int[] family = { 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4 }; int n = family.Length; Console.WriteLine("n = {0}", n); @@ -92,17 +92,14 @@ public class SecretSanta { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_SIMPLE); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_SIMPLE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); foreach (int i in RANGE) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -115,5 +112,7 @@ public class SecretSanta { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/secret_santa2.cs b/examples/contrib/secret_santa2.cs index a774f1718c..7df70c93be 100644 --- a/examples/contrib/secret_santa2.cs +++ b/examples/contrib/secret_santa2.cs @@ -80,15 +80,15 @@ public class SecretSanta2 { int n_no_single = 8; int M = n_no_single + 1; int[][] rounds_no_single = { - // N A R M El J L Ev - new int[]{0, M, 3, M, 1, 4, M, 2}, // Noah - new int[]{M, 0, 4, 2, M, 3, M, 1}, // Ava - new int[]{M, 2, 0, M, 1, M, 3, 4}, // Ryan - new int[]{M, 1, M, 0, 2, M, 3, 4}, // Mia - new int[]{M, 4, M, 3, 0, M, 1, 2}, // Ella - new int[]{1, 4, 3, M, M, 0, 2, M}, // John - new int[]{M, 3, M, 2, 4, 1, 0, M}, // Lily - new int[]{4, M, 3, 1, M, 2, M, 0} // Evan + // N A R M El J L Ev + new int[] { 0, M, 3, M, 1, 4, M, 2 }, // Noah + new int[] { M, 0, 4, 2, M, 3, M, 1 }, // Ava + new int[] { M, 2, 0, M, 1, M, 3, 4 }, // Ryan + new int[] { M, 1, M, 0, 2, M, 3, 4 }, // Mia + new int[] { M, 4, M, 3, 0, M, 1, 2 }, // Ella + new int[] { 1, 4, 3, M, M, 0, 2, M }, // John + new int[] { M, 3, M, 2, 4, 1, 0, M }, // Lily + new int[] { 4, M, 3, 1, M, 2, M, 0 } // Evan }; // @@ -97,16 +97,16 @@ public class SecretSanta2 { int n_with_single = 9; M = n_with_single + 1; int[][] rounds_single = { - // N A R M El J L Ev S - new int[]{0, M, 3, M, 1, 4, M, 2, 2}, // Noah - new int[]{M, 0, 4, 2, M, 3, M, 1, 1}, // Ava - new int[]{M, 2, 0, M, 1, M, 3, 4, 4}, // Ryan - new int[]{M, 1, M, 0, 2, M, 3, 4, 3}, // Mia - new int[]{M, 4, M, 3, 0, M, 1, 2, M}, // Ella - new int[]{1, 4, 3, M, M, 0, 2, M, M}, // John - new int[]{M, 3, M, 2, 4, 1, 0, M, M}, // Lily - new int[]{4, M, 3, 1, M, 2, M, 0, M}, // Evan - new int[]{1, 2, 3, 4, M, 2, M, M, 0} // Single + // N A R M El J L Ev S + new int[] { 0, M, 3, M, 1, 4, M, 2, 2 }, // Noah + new int[] { M, 0, 4, 2, M, 3, M, 1, 1 }, // Ava + new int[] { M, 2, 0, M, 1, M, 3, 4, 4 }, // Ryan + new int[] { M, 1, M, 0, 2, M, 3, 4, 3 }, // Mia + new int[] { M, 4, M, 3, 0, M, 1, 2, M }, // Ella + new int[] { 1, 4, 3, M, M, 0, 2, M, M }, // John + new int[] { M, 3, M, 2, 4, 1, 0, M, M }, // Lily + new int[] { 4, M, 3, 1, M, 2, M, 0, M }, // Evan + new int[] { 1, 2, 3, 4, M, 2, M, M, 0 } // Single }; int Noah = 0; @@ -129,19 +129,18 @@ public class SecretSanta2 { IEnumerable RANGE = Enumerable.Range(0, n); - String[] persons = {"Noah", "Ava", "Ryan", "Mia", "Ella", - "John", "Lily", "Evan", "Single"}; + String[] persons = { "Noah", "Ava", "Ryan", "Mia", "Ella", "John", "Lily", "Evan", "Single" }; int[] spouses = { - Ava, // Noah - Noah, // Ava - Mia, // Rya - Ryan, // Mia - John, // Ella - Ella, // John - Evan, // Lily - Lily, // Evan - -1 // Single has no spouse + Ava, // Noah + Noah, // Ava + Mia, // Rya + Ryan, // Mia + John, // Ella + Ella, // John + Evan, // Lily + Lily, // Evan + -1 // Single has no spouse }; // @@ -173,16 +172,14 @@ public class SecretSanta2 { // optimize "distance" to earlier rounds: foreach (int i in RANGE) { - solver.Add(santa_distance[i] == rounds [i] - .Element(santas[i])); + solver.Add(santa_distance[i] == rounds[i].Element(santas[i])); } // cannot be a Secret Santa for the same person // two years in a row. foreach (int i in RANGE) { foreach (int j in RANGE) { - if (rounds [i] - [j] == 1) { + if (rounds[i][j] == 1) { solver.Add(santas[i] != j); } } @@ -196,8 +193,8 @@ public class SecretSanta2 { // // Search // - DecisionBuilder db = solver.MakePhase( - santas, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); + DecisionBuilder db = + solver.MakePhase(santas, Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_CENTER_VALUE); solver.NewSearch(db, obj); @@ -205,18 +202,12 @@ public class SecretSanta2 { Console.WriteLine("\ntotal distances: {0}", z.Value()); Console.Write("santas: "); for (int i = 0; i < n; i++) { - Console.Write(santas [i] - .Value() + - " "); + Console.Write(santas[i].Value() + " "); } Console.WriteLine(); foreach (int i in RANGE) { Console.WriteLine("{0}\tis a Santa to {1} (distance {2})", persons[i], - persons [santas [i] - .Value()] - , - santa_distance [i] - .Value()); + persons[santas[i].Value()], santa_distance[i].Value()); } } diff --git a/examples/contrib/send_more_money.cs b/examples/contrib/send_more_money.cs index ff2599a2c7..23d5bff1ac 100644 --- a/examples/contrib/send_more_money.cs +++ b/examples/contrib/send_more_money.cs @@ -38,14 +38,13 @@ public class SendMoreMoney { IntVar Y = solver.MakeIntVar(0, 9, "Y"); // for AllDifferent() - IntVar[] x = new IntVar[]{S, E, N, D, M, O, R, Y}; + IntVar[] x = new IntVar[] { S, E, N, D, M, O, R, Y }; // // Constraints // solver.Add(x.AllDifferent()); - solver.Add(S * 1000 + E * 100 + N * 10 + D + M * 1000 + O * 100 + R * 10 + - E == + solver.Add(S * 1000 + E * 100 + N * 10 + D + M * 1000 + O * 100 + R * 10 + E == M * 10000 + O * 1000 + N * 100 + E * 10 + Y); solver.Add(S > 0); @@ -54,15 +53,12 @@ public class SendMoreMoney { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < 8; i++) { - Console.Write(x [i] - .ToString() + - " "); + Console.Write(x[i].ToString() + " "); } Console.WriteLine(); } @@ -74,5 +70,7 @@ public class SendMoreMoney { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/send_more_money2.cs b/examples/contrib/send_more_money2.cs index 59685925e6..3f19b45b42 100644 --- a/examples/contrib/send_more_money2.cs +++ b/examples/contrib/send_more_money2.cs @@ -39,7 +39,7 @@ public class SendMoreMoney { IntVar Y = solver.MakeIntVar(0, 9, "Y"); // for AllDifferent() - IntVar[] x = new IntVar[]{S, E, N, D, M, O, R, Y}; + IntVar[] x = new IntVar[] { S, E, N, D, M, O, R, Y }; // // Constraints @@ -52,11 +52,11 @@ public class SendMoreMoney { */ // Here we use scalar product instead. - int[] s1 = new int[]{1000, 100, 10, 1}; - int[] s2 = new int[]{10000, 1000, 100, 10, 1}; - solver.Add(new IntVar[]{S, E, N, D}.ScalProd(s1) + - new IntVar[]{M, O, R, E}.ScalProd(s1) == - new IntVar[]{M, O, N, E, Y}.ScalProd(s2)); + int[] s1 = new int[] { 1000, 100, 10, 1 }; + int[] s2 = new int[] { 10000, 1000, 100, 10, 1 }; + solver.Add(new IntVar[] { S, E, N, D }.ScalProd(s1) + + new IntVar[] { M, O, R, E }.ScalProd(s1) == + new IntVar[] { M, O, N, E, Y }.ScalProd(s2)); solver.Add(S > 0); solver.Add(M > 0); @@ -64,15 +64,12 @@ public class SendMoreMoney { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < 8; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -85,5 +82,7 @@ public class SendMoreMoney { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/send_most_money.cs b/examples/contrib/send_most_money.cs index 5fcec23708..d0f37ca148 100644 --- a/examples/contrib/send_most_money.cs +++ b/examples/contrib/send_most_money.cs @@ -40,22 +40,21 @@ public class SendMostMoney { IntVar Y = solver.MakeIntVar(0, 9, "Y"); // for AllDifferent() - IntVar[] x = new IntVar[]{S, E, N, D, M, O, T, Y}; + IntVar[] x = new IntVar[] { S, E, N, D, M, O, T, Y }; - IntVar[] eq = {S, E, N, D, M, O, S, T, M, O, N, E, Y}; + IntVar[] eq = { S, E, N, D, M, O, S, T, M, O, N, E, Y }; int[] coeffs = { - 1000, 100, 10, 1, // S E N D + - 1000, 100, 10, 1, // M O S T - -10000, -1000, -100, -10, -1 // == M O N E Y + 1000, 100, 10, 1, // S E N D + + 1000, 100, 10, 1, // M O S T + -10000, -1000, -100, -10, -1 // == M O N E Y }; solver.Add(eq.ScalProd(coeffs) == 0); // IntVar money = solver.MakeScalProd(new IntVar[] {M, O, N, E, Y}, // new int[] {10000, 1000, 100, 10, // 1}).Var(); - IntVar money = (new IntVar[]{M, O, N, E, Y}) - .ScalProd(new int[]{10000, 1000, 100, 10, 1}) - .Var(); + IntVar money = + (new IntVar[] { M, O, N, E, Y }).ScalProd(new int[] { 10000, 1000, 100, 10, 1 }).Var(); // // Constraints @@ -71,8 +70,7 @@ public class SendMostMoney { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); if (MONEY == 0) { OptimizeVar obj = money.Maximize(1); @@ -86,9 +84,7 @@ public class SendMostMoney { money_ret = money.Value(); Console.WriteLine("money: {0}", money.Value()); for (int i = 0; i < x.Length; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -106,8 +102,7 @@ public class SendMostMoney { public static void Main(String[] args) { Console.WriteLine("First get the max value of money:"); long this_money = Solve(0); - Console.WriteLine("\nThen we find all solutions for MONEY = {0}:", - this_money); + Console.WriteLine("\nThen we find all solutions for MONEY = {0}:", this_money); long tmp = Solve(this_money); } } diff --git a/examples/contrib/seseman.cs b/examples/contrib/seseman.cs index 2e5e268f75..410225146d 100644 --- a/examples/contrib/seseman.cs +++ b/examples/contrib/seseman.cs @@ -34,7 +34,7 @@ public class Seseman { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 0, n * n, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 0, n * n, "x"); IntVar[] x_flat = x.Flatten(); IntVar total_sum = x_flat.Sum().Var(); @@ -77,16 +77,14 @@ public class Seseman { // // Search // - DecisionBuilder db = - solver.MakePhase(x_flat, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_PATH, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.WriteLine("total_sum: {0} ", total_sum.Value()); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write("{0} ", x [i, j] - .Value()); + Console.Write("{0} ", x[i, j].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/set_covering.cs b/examples/contrib/set_covering.cs index 3c034878fa..e78db3f231 100644 --- a/examples/contrib/set_covering.cs +++ b/examples/contrib/set_covering.cs @@ -39,9 +39,9 @@ public class SetCovering { int min_distance = 15; int num_cities = 6; - int[, ] distance = {{0, 10, 20, 30, 30, 20}, {10, 0, 25, 35, 20, 10}, - {20, 25, 0, 15, 30, 20}, {30, 35, 15, 0, 15, 25}, - {30, 20, 30, 15, 0, 14}, {20, 10, 20, 25, 14, 0}}; + int[,] distance = { { 0, 10, 20, 30, 30, 20 }, { 10, 0, 25, 35, 20, 10 }, + { 20, 25, 0, 15, 30, 20 }, { 30, 35, 15, 0, 15, 25 }, + { 30, 20, 30, 15, 0, 14 }, { 20, 10, 20, 25, 14, 0 } }; // // Decision variables @@ -69,8 +69,7 @@ public class SetCovering { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); @@ -78,9 +77,7 @@ public class SetCovering { Console.WriteLine("z: {0}", z.Value()); Console.Write("x: "); for (int i = 0; i < num_cities; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -93,5 +90,7 @@ public class SetCovering { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/set_covering2.cs b/examples/contrib/set_covering2.cs index d2c92d7c2d..c6579155bf 100644 --- a/examples/contrib/set_covering2.cs +++ b/examples/contrib/set_covering2.cs @@ -44,8 +44,8 @@ public class SetCovering2 { // corners of each street // Note: 1-based (handled below) - int[, ] corner = {{1, 2}, {2, 3}, {4, 5}, {7, 8}, {6, 7}, {2, 6}, - {1, 6}, {4, 7}, {2, 4}, {5, 8}, {3, 5}}; + int[,] corner = { { 1, 2 }, { 2, 3 }, { 4, 5 }, { 7, 8 }, { 6, 7 }, { 2, 6 }, + { 1, 6 }, { 4, 7 }, { 2, 4 }, { 5, 8 }, { 3, 5 } }; // // Decision variables @@ -71,8 +71,7 @@ public class SetCovering2 { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); @@ -80,9 +79,7 @@ public class SetCovering2 { Console.WriteLine("z: {0}", z.Value()); Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -95,5 +92,7 @@ public class SetCovering2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/set_covering3.cs b/examples/contrib/set_covering3.cs index c4c30f166f..ee22a56e7d 100644 --- a/examples/contrib/set_covering3.cs +++ b/examples/contrib/set_covering3.cs @@ -41,12 +41,12 @@ public class SetCovering3 { int num_senators = 10; // which group does a senator belong to? - int[, ] belongs = {{1, 1, 1, 1, 1, 0, 0, 0, 0, 0}, // 1 southern - {0, 0, 0, 0, 0, 1, 1, 1, 1, 1}, // 2 northern - {0, 1, 1, 0, 0, 0, 0, 1, 1, 1}, // 3 liberals - {1, 0, 0, 0, 1, 1, 1, 0, 0, 0}, // 4 conservative - {0, 0, 1, 1, 1, 1, 1, 0, 1, 0}, // 5 democrats - {1, 1, 0, 0, 0, 0, 0, 1, 0, 1}}; // 6 republicans + int[,] belongs = { { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }, // 1 southern + { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 }, // 2 northern + { 0, 1, 1, 0, 0, 0, 0, 1, 1, 1 }, // 3 liberals + { 1, 0, 0, 0, 1, 1, 1, 0, 0, 0 }, // 4 conservative + { 0, 0, 1, 1, 1, 1, 1, 0, 1, 0 }, // 5 democrats + { 1, 1, 0, 0, 0, 0, 0, 1, 0, 1 } }; // 6 republicans // // Decision variables @@ -77,8 +77,7 @@ public class SetCovering3 { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); @@ -86,16 +85,13 @@ public class SetCovering3 { Console.WriteLine("z: " + z.Value()); Console.Write("x: "); for (int j = 0; j < num_senators; j++) { - Console.Write(x [j] - .Value() + - " "); + Console.Write(x[j].Value() + " "); } Console.WriteLine(); // More details for (int j = 0; j < num_senators; j++) { - if (x [j] - .Value() == 1) { + if (x[j].Value() == 1) { Console.Write("Senator " + (1 + j) + " belongs to these groups: "); for (int i = 0; i < num_groups; i++) { if (belongs[i, j] == 1) { @@ -115,5 +111,7 @@ public class SetCovering3 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/set_covering4.cs b/examples/contrib/set_covering4.cs index 067449f96b..4ac5dc2d49 100644 --- a/examples/contrib/set_covering4.cs +++ b/examples/contrib/set_covering4.cs @@ -42,20 +42,21 @@ public class SetCovering4 { int num_objects = 8; // costs for the alternatives - int[] costs = {19, 16, 18, 13, 15, 19, 15, 17, 16, 15}; + int[] costs = { 19, 16, 18, 13, 15, 19, 15, 17, 16, 15 }; // the alternatives, and their objects - int[, ] a = { // 1 2 3 4 5 6 7 8 the objects - {1, 0, 0, 0, 0, 1, 0, 0}, // alternative 1 - {0, 1, 0, 0, 0, 1, 0, 1}, // alternative 2 - {1, 0, 0, 1, 0, 0, 1, 0}, // alternative 3 - {0, 1, 1, 0, 1, 0, 0, 0}, // alternative 4 - {0, 1, 0, 0, 1, 0, 0, 0}, // alternative 5 - {0, 1, 1, 0, 0, 0, 0, 0}, // alternative 6 - {0, 1, 1, 1, 0, 0, 0, 0}, // alternative 7 - {0, 0, 0, 1, 1, 0, 0, 1}, // alternative 8 - {0, 0, 1, 0, 0, 1, 0, 1}, // alternative 9 - {1, 0, 0, 0, 0, 1, 1, 0}}; // alternative 10 + int[,] a = { // 1 2 3 4 5 6 7 8 the objects + { 1, 0, 0, 0, 0, 1, 0, 0 }, // alternative 1 + { 0, 1, 0, 0, 0, 1, 0, 1 }, // alternative 2 + { 1, 0, 0, 1, 0, 0, 1, 0 }, // alternative 3 + { 0, 1, 1, 0, 1, 0, 0, 0 }, // alternative 4 + { 0, 1, 0, 0, 1, 0, 0, 0 }, // alternative 5 + { 0, 1, 1, 0, 0, 0, 0, 0 }, // alternative 6 + { 0, 1, 1, 1, 0, 0, 0, 0 }, // alternative 7 + { 0, 0, 0, 1, 1, 0, 0, 1 }, // alternative 8 + { 0, 0, 1, 0, 0, 1, 0, 1 }, // alternative 9 + { 1, 0, 0, 0, 0, 1, 1, 0 } + }; // alternative 10 // // Decision variables @@ -89,8 +90,7 @@ public class SetCovering4 { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); @@ -98,8 +98,7 @@ public class SetCovering4 { Console.WriteLine("z: " + z.Value()); Console.Write("Selected alternatives: "); for (int i = 0; i < num_alternatives; i++) { - if (x [i] - .Value() == 1) { + if (x[i].Value() == 1) { Console.Write((i + 1) + " "); } } diff --git a/examples/contrib/set_covering_deployment.cs b/examples/contrib/set_covering_deployment.cs index 19605cde79..6652e3dc96 100644 --- a/examples/contrib/set_covering_deployment.cs +++ b/examples/contrib/set_covering_deployment.cs @@ -35,16 +35,16 @@ public class SetCoveringDeployment { // // From http://mathworld.wolfram.com/SetCoveringDeployment.html - string[] countries = {"Alexandria", "Asia Minor", "Britain", "Byzantium", - "Gaul", "Iberia", "Rome", "Tunis"}; + string[] countries = { "Alexandria", "Asia Minor", "Britain", "Byzantium", + "Gaul", "Iberia", "Rome", "Tunis" }; int n = countries.Length; // the incidence matrix (neighbours) - int[, ] mat = {{0, 1, 0, 1, 0, 0, 1, 1}, {1, 0, 0, 1, 0, 0, 0, 0}, - {0, 0, 0, 0, 1, 1, 0, 0}, {1, 1, 0, 0, 0, 0, 1, 0}, - {0, 0, 1, 0, 0, 1, 1, 0}, {0, 0, 1, 0, 1, 0, 1, 1}, - {1, 0, 0, 1, 1, 1, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 0}}; + int[,] mat = { { 0, 1, 0, 1, 0, 0, 1, 1 }, { 1, 0, 0, 1, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 1, 1, 0, 0 }, { 1, 1, 0, 0, 0, 0, 1, 0 }, + { 0, 0, 1, 0, 0, 1, 1, 0 }, { 0, 0, 1, 0, 1, 0, 1, 1 }, + { 1, 0, 0, 1, 1, 1, 0, 1 }, { 1, 0, 0, 0, 0, 1, 1, 0 } }; // // Decision variables @@ -93,21 +93,18 @@ public class SetCoveringDeployment { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, objective); while (solver.NextSolution()) { Console.WriteLine("num_armies: " + num_armies.Value()); for (int i = 0; i < n; i++) { - if (x [i] - .Value() == 1) { + if (x[i].Value() == 1) { Console.Write("Army: " + countries[i] + " "); } - if (y [i] - .Value() == 1) { + if (y[i].Value() == 1) { Console.WriteLine(" Reverse army: " + countries[i]); } } @@ -122,5 +119,7 @@ public class SetCoveringDeployment { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/set_covering_skiena.cs b/examples/contrib/set_covering_skiena.cs index dcbe2ea978..733367ffc0 100644 --- a/examples/contrib/set_covering_skiena.cs +++ b/examples/contrib/set_covering_skiena.cs @@ -47,15 +47,15 @@ public class SetCoveringSkiena { IEnumerable Elements = Enumerable.Range(0, num_elements); // Which element belongs to which set - int[, ] belongs = { - // 1 2 3 4 5 6 7 8 9 0 1 2 elements - {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Set 1 - {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, // 2 - {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, // 3 - {0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0}, // 4 - {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0}, // 5 - {1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0}, // 6 - {0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1} // 7 + int[,] belongs = { + // 1 2 3 4 5 6 7 8 9 0 1 2 elements + { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Set 1 + { 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, // 2 + { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, // 3 + { 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, // 4 + { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0 }, // 5 + { 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0 }, // 6 + { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1 } // 7 }; // @@ -64,8 +64,7 @@ public class SetCoveringSkiena { IntVar[] x = solver.MakeIntVarArray(num_sets, 0, 1, "x"); IntVar z = x.Sum().VarWithName("z"); // total number of elements in the choosen sets - IntVar tot_elements = - solver.MakeIntVar(0, num_sets * num_elements, "tot_elements"); + IntVar tot_elements = solver.MakeIntVar(0, num_sets * num_elements, "tot_elements"); // // Constraints @@ -73,14 +72,12 @@ public class SetCoveringSkiena { // all sets must be used foreach (int j in Elements) { - solver.Add((from i in Sets select belongs[i, j] * x[i]).ToArray().Sum() >= - 1); + solver.Add((from i in Sets select belongs[i, j] * x[i]).ToArray().Sum() >= 1); } // number of used elements - solver.Add((from i in Sets from j in Elements select x[i] * belongs[i, j]) - .ToArray() - .Sum() == tot_elements); + solver.Add((from i in Sets from j in Elements select x[i] * belongs[i, j]).ToArray().Sum() == + tot_elements); // // Objective @@ -90,20 +87,18 @@ public class SetCoveringSkiena { // // Search // - DecisionBuilder db = - solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("z: {0}", z.Value()); Console.WriteLine("tot_elements: {0}", tot_elements.Value()); - Console.WriteLine("x: {0}", - String.Join(" ", (from i in Enumerable - .Range(0, num_sets) select x [i] - .Value() - .ToString()) - .ToArray())); + Console.WriteLine( + "x: {0}", + String.Join( + " ", + (from i in Enumerable.Range(0, num_sets) select x[i].Value().ToString()).ToArray())); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); @@ -114,5 +109,7 @@ public class SetCoveringSkiena { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/set_partition.cs b/examples/contrib/set_partition.cs index 9d4c6f2b00..cefce5b95d 100644 --- a/examples/contrib/set_partition.cs +++ b/examples/contrib/set_partition.cs @@ -23,27 +23,24 @@ public class SetPartition { // // Partition the sets (binary matrix representation). // - public static void partition_sets(Solver solver, IntVar[, ] x, int num_sets, - int n) { + public static void partition_sets(Solver solver, IntVar[,] x, int num_sets, int n) { for (int i = 0; i < num_sets; i++) { for (int j = 0; j < num_sets; j++) { if (i != j) { // b = solver.Sum([x[i,k]*x[j,k] for k in range(n)]); // solver.Add(b == 0); - solver.Add( - (from k in Enumerable.Range(0, n) select(x[i, k] * x[j, k])) - .ToArray() - .Sum() == 0); + solver.Add((from k in Enumerable.Range(0, n) select(x[i, k] * x[j, k])).ToArray().Sum() == + 0); } } } // ensure that all integers is in // (exactly) one partition - solver.Add((from i in Enumerable.Range(0, num_sets) - from j in Enumerable.Range(0, n) select x[i, j]) - .ToArray() - .Sum() == n); + solver.Add( + (from i in Enumerable.Range(0, num_sets) from j in Enumerable.Range(0, n) select x[i, j]) + .ToArray() + .Sum() == n); } /** @@ -82,7 +79,7 @@ public class SetPartition { // // Decision variables // - IntVar[, ] a = solver.MakeIntVarMatrix(num_sets, n, 0, 1, "a"); + IntVar[,] a = solver.MakeIntVarMatrix(num_sets, n, 0, 1, "a"); IntVar[] a_flat = a.Flatten(); // @@ -103,12 +100,8 @@ public class SetPartition { (from k in NRange select(k * a[j, k])).ToArray().Sum()); // same sum squared - solver.Add((from k in NRange select(k * a[i, k] * k * a[i, k])) - .ToArray() - .Sum() == - (from k in NRange select(k * a[j, k] * k * a[j, k])) - .ToArray() - .Sum()); + solver.Add((from k in NRange select(k * a[i, k] * k * a[i, k])).ToArray().Sum() == + (from k in NRange select(k * a[j, k] * k * a[j, k])).ToArray().Sum()); } } @@ -120,28 +113,23 @@ public class SetPartition { // // Search // - DecisionBuilder db = solver.MakePhase(a_flat, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(a_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { - int[, ] a_val = new int[num_sets, n]; + int[,] a_val = new int[num_sets, n]; foreach (int i in Sets) { foreach (int j in NRange) { - a_val[i, j] = (int) a [i, j] - .Value(); + a_val[i, j] = (int)a[i, j].Value(); } } - Console.WriteLine( - "sums: {0}", - (from j in NRange select(j + 1) * a_val[0, j]).ToArray().Sum()); + Console.WriteLine("sums: {0}", + (from j in NRange select(j + 1) * a_val[0, j]).ToArray().Sum()); Console.WriteLine( "sums squared: {0}", - (from j in NRange select(int) Math.Pow((j + 1) * a_val[0, j], 2)) - .ToArray() - .Sum()); + (from j in NRange select(int) Math.Pow((j + 1) * a_val[0, j], 2)).ToArray().Sum()); // Show the numbers in each set foreach (int i in Sets) { @@ -181,8 +169,7 @@ public class SetPartition { if (n % num_sets == 0) { Solve(n, num_sets); } else { - Console.WriteLine("n {0} num_sets {1}: Equal sets is not possible!", n, - num_sets); + Console.WriteLine("n {0} num_sets {1}: Equal sets is not possible!", n, num_sets); } } } diff --git a/examples/contrib/sicherman_dice.cs b/examples/contrib/sicherman_dice.cs index 4a67c53b12..fb5136c770 100644 --- a/examples/contrib/sicherman_dice.cs +++ b/examples/contrib/sicherman_dice.cs @@ -74,7 +74,7 @@ public class SichermanDice { int lowest_value = 0; // standard distribution - int[] standard_dist = {1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1}; + int[] standard_dist = { 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 }; IEnumerable RANGE = Enumerable.Range(0, n); IEnumerable RANGE1 = Enumerable.Range(0, n - 1); @@ -90,9 +90,8 @@ public class SichermanDice { // Constraints // for (int k = 0; k < standard_dist.Length; k++) { - solver.Add((from i in RANGE from j in RANGE select x1[i] + x2[j] == k + 2) - .ToArray() - .Sum() == standard_dist[k]); + solver.Add((from i in RANGE from j in RANGE select x1[i] + x2[j] == k + 2).ToArray().Sum() == + standard_dist[k]); } // symmetry breaking @@ -106,23 +105,18 @@ public class SichermanDice { // Search // DecisionBuilder db = - solver.MakePhase(x1.Concat(x2).ToArray(), Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + solver.MakePhase(x1.Concat(x2).ToArray(), Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x1: "); foreach (int i in RANGE) { - Console.Write(x1 [i] - .Value() + - " "); + Console.Write(x1[i].Value() + " "); } Console.Write("\nx2: "); foreach (int i in RANGE) { - Console.Write(x2 [i] - .Value() + - " "); + Console.Write(x2[i].Value() + " "); } Console.WriteLine("\n"); } @@ -135,5 +129,7 @@ public class SichermanDice { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/ski_assignment.cs b/examples/contrib/ski_assignment.cs index d8e50c0721..672b0c2fd0 100644 --- a/examples/contrib/ski_assignment.cs +++ b/examples/contrib/ski_assignment.cs @@ -57,8 +57,8 @@ public class SkiAssignment { // int num_skis = 6; int num_skiers = 5; - int[] ski_heights = {1, 2, 5, 7, 13, 21}; - int[] skier_heights = {3, 4, 7, 11, 18}; + int[] ski_heights = { 1, 2, 5, 7, 13, 21 }; + int[] skier_heights = { 3, 4, 7, 11, 18 }; // // Decision variables @@ -89,17 +89,14 @@ public class SkiAssignment { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.Write("z: {0} x: ", z.Value()); for (int i = 0; i < num_skiers; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -112,5 +109,7 @@ public class SkiAssignment { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/stable_marriage.cs b/examples/contrib/stable_marriage.cs index e1513a59a9..b6a8e1593d 100644 --- a/examples/contrib/stable_marriage.cs +++ b/examples/contrib/stable_marriage.cs @@ -69,12 +69,8 @@ public class StableMarriage { // rankWomen[o,husband[o]] < rankWomen[o,m]); for (int m = 0; m < n; m++) { for (int o = 0; o < n; o++) { - IntVar b1 = rankMen [m] - .Element(wife[m]) > rankMen [m] - [o]; - IntVar b2 = rankWomen [o] - .Element(husband[o]) < rankWomen [o] - [m]; + IntVar b1 = rankMen[m].Element(wife[m]) > rankMen[m][o]; + IntVar b2 = rankWomen[o].Element(husband[o]) < rankWomen[o][m]; solver.Add(b1 <= b2); } } @@ -84,12 +80,8 @@ public class StableMarriage { // rankMen[o,wife[o]] < rankMen[o,w]); for (int w = 0; w < n; w++) { for (int o = 0; o < n; o++) { - IntVar b1 = rankWomen [w] - .Element(husband[w]) > rankWomen [w] - [o]; - IntVar b2 = rankMen [o] - .Element(wife[o]) < rankMen [o] - [w]; + IntVar b1 = rankWomen[w].Element(husband[w]) > rankWomen[w][o]; + IntVar b2 = rankMen[o].Element(wife[o]) < rankMen[o][w]; solver.Add(b1 <= b2); } } @@ -97,23 +89,18 @@ public class StableMarriage { // // Search // - DecisionBuilder db = solver.MakePhase(wife, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(wife, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("wife : "); for (int i = 0; i < n; i++) { - Console.Write(wife [i] - .Value() + - " "); + Console.Write(wife[i].Value() + " "); } Console.Write("\nhusband: "); for (int i = 0; i < n; i++) { - Console.Write(husband [i] - .Value() + - " "); + Console.Write(husband[i].Value() + " "); } Console.WriteLine("\n"); } @@ -131,54 +118,53 @@ public class StableMarriage { // From Pascal Van Hentenryck's OPL book // int[][][] van_hentenryck = { - // rankWomen - new int[][]{new int[]{1, 2, 4, 3, 5}, new int[]{3, 5, 1, 2, 4}, - new int[]{5, 4, 2, 1, 3}, new int[]{1, 3, 5, 4, 2}, - new int[]{4, 2, 3, 5, 1}}, + // rankWomen + new int[][] { new int[] { 1, 2, 4, 3, 5 }, new int[] { 3, 5, 1, 2, 4 }, + new int[] { 5, 4, 2, 1, 3 }, new int[] { 1, 3, 5, 4, 2 }, + new int[] { 4, 2, 3, 5, 1 } }, - // rankMen - new int[][]{new int[]{5, 1, 2, 4, 3}, new int[]{4, 1, 3, 2, 5}, - new int[]{5, 3, 2, 4, 1}, new int[]{1, 5, 4, 3, 2}, - new int[]{4, 3, 2, 1, 5}}}; + // rankMen + new int[][] { new int[] { 5, 1, 2, 4, 3 }, new int[] { 4, 1, 3, 2, 5 }, + new int[] { 5, 3, 2, 4, 1 }, new int[] { 1, 5, 4, 3, 2 }, + new int[] { 4, 3, 2, 1, 5 } } + }; // // Data from MathWorld // http://mathworld.wolfram.com/StableMarriageProblem.html // - int[][][] mathworld = {// rankWomen - new int[][]{new int[]{3, 1, 5, 2, 8, 7, 6, 9, 4}, - new int[]{9, 4, 8, 1, 7, 6, 3, 2, 5}, - new int[]{3, 1, 8, 9, 5, 4, 2, 6, 7}, - new int[]{8, 7, 5, 3, 2, 6, 4, 9, 1}, - new int[]{6, 9, 2, 5, 1, 4, 7, 3, 8}, - new int[]{2, 4, 5, 1, 6, 8, 3, 9, 7}, - new int[]{9, 3, 8, 2, 7, 5, 4, 6, 1}, - new int[]{6, 3, 2, 1, 8, 4, 5, 9, 7}, - new int[]{8, 2, 6, 4, 9, 1, 3, 7, 5}}, + int[][][] mathworld = { + // rankWomen + new int[][] { + new int[] { 3, 1, 5, 2, 8, 7, 6, 9, 4 }, new int[] { 9, 4, 8, 1, 7, 6, 3, 2, 5 }, + new int[] { 3, 1, 8, 9, 5, 4, 2, 6, 7 }, new int[] { 8, 7, 5, 3, 2, 6, 4, 9, 1 }, + new int[] { 6, 9, 2, 5, 1, 4, 7, 3, 8 }, new int[] { 2, 4, 5, 1, 6, 8, 3, 9, 7 }, + new int[] { 9, 3, 8, 2, 7, 5, 4, 6, 1 }, new int[] { 6, 3, 2, 1, 8, 4, 5, 9, 7 }, + new int[] { 8, 2, 6, 4, 9, 1, 3, 7, 5 } + }, - // rankMen - new int[][]{new int[]{7, 3, 8, 9, 6, 4, 2, 1, 5}, - new int[]{5, 4, 8, 3, 1, 2, 6, 7, 9}, - new int[]{4, 8, 3, 9, 7, 5, 6, 1, 2}, - new int[]{9, 7, 4, 2, 5, 8, 3, 1, 6}, - new int[]{2, 6, 4, 9, 8, 7, 5, 1, 3}, - new int[]{2, 7, 8, 6, 5, 3, 4, 1, 9}, - new int[]{1, 6, 2, 3, 8, 5, 4, 9, 7}, - new int[]{5, 6, 9, 1, 2, 8, 4, 3, 7}, - new int[]{6, 1, 4, 7, 5, 8, 3, 9, 2}}}; + // rankMen + new int[][] { + new int[] { 7, 3, 8, 9, 6, 4, 2, 1, 5 }, new int[] { 5, 4, 8, 3, 1, 2, 6, 7, 9 }, + new int[] { 4, 8, 3, 9, 7, 5, 6, 1, 2 }, new int[] { 9, 7, 4, 2, 5, 8, 3, 1, 6 }, + new int[] { 2, 6, 4, 9, 8, 7, 5, 1, 3 }, new int[] { 2, 7, 8, 6, 5, 3, 4, 1, 9 }, + new int[] { 1, 6, 2, 3, 8, 5, 4, 9, 7 }, new int[] { 5, 6, 9, 1, 2, 8, 4, 3, 7 }, + new int[] { 6, 1, 4, 7, 5, 8, 3, 9, 2 } + } + }; // // Data from // http://www.csee.wvu.edu/~ksmani/courses/fa01/random/lecnotes/lecture5.pdf // - int[][][] problem3 = { - // rankWomen - new int[][]{new int[]{1, 2, 3, 4}, new int[]{4, 3, 2, 1}, - new int[]{1, 2, 3, 4}, new int[]{3, 4, 1, 2}}, + int[][][] problem3 = {// rankWomen + new int[][] { new int[] { 1, 2, 3, 4 }, new int[] { 4, 3, 2, 1 }, + new int[] { 1, 2, 3, 4 }, new int[] { 3, 4, 1, 2 } }, - // rankMen - new int[][]{new int[]{1, 2, 3, 4}, new int[]{2, 1, 3, 4}, - new int[]{1, 4, 3, 2}, new int[]{4, 3, 1, 2}}}; + // rankMen + new int[][] { new int[] { 1, 2, 3, 4 }, new int[] { 2, 1, 3, 4 }, + new int[] { 1, 4, 3, 2 }, new int[] { 4, 3, 1, 2 } } + }; // // Data from @@ -186,15 +172,16 @@ public class StableMarriage { // page 4 // int[][][] problem4 = { - // rankWomen - new int[][]{new int[]{1, 5, 4, 6, 2, 3}, new int[]{4, 1, 5, 2, 6, 3}, - new int[]{6, 4, 2, 1, 5, 3}, new int[]{1, 5, 2, 4, 3, 6}, - new int[]{4, 2, 1, 5, 6, 3}, new int[]{2, 6, 3, 5, 1, 4}}, + // rankWomen + new int[][] { new int[] { 1, 5, 4, 6, 2, 3 }, new int[] { 4, 1, 5, 2, 6, 3 }, + new int[] { 6, 4, 2, 1, 5, 3 }, new int[] { 1, 5, 2, 4, 3, 6 }, + new int[] { 4, 2, 1, 5, 6, 3 }, new int[] { 2, 6, 3, 5, 1, 4 } }, - // rankMen - new int[][]{new int[]{1, 4, 2, 5, 6, 3}, new int[]{3, 4, 6, 1, 5, 2}, - new int[]{1, 6, 4, 2, 3, 5}, new int[]{6, 5, 3, 4, 2, 1}, - new int[]{3, 1, 2, 4, 5, 6}, new int[]{2, 3, 1, 6, 5, 4}}}; + // rankMen + new int[][] { new int[] { 1, 4, 2, 5, 6, 3 }, new int[] { 3, 4, 6, 1, 5, 2 }, + new int[] { 1, 6, 4, 2, 3, 5 }, new int[] { 6, 5, 3, 4, 2, 1 }, + new int[] { 3, 1, 2, 4, 5, 6 }, new int[] { 2, 3, 1, 6, 5, 4 } } + }; Solve(van_hentenryck, "Van Hentenryck"); Solve(mathworld, "MathWorld"); diff --git a/examples/contrib/strimko2.cs b/examples/contrib/strimko2.cs index cdb9e79e9e..3d29f3db6b 100644 --- a/examples/contrib/strimko2.cs +++ b/examples/contrib/strimko2.cs @@ -33,14 +33,13 @@ public class Strimko2 { // // data // - int[, ] streams = {{1, 1, 2, 2, 2, 2, 2}, {1, 1, 2, 3, 3, 3, 2}, - {1, 4, 1, 3, 3, 5, 5}, {4, 4, 3, 1, 3, 5, 5}, - {4, 6, 6, 6, 7, 7, 5}, {6, 4, 6, 4, 5, 5, 7}, - {6, 6, 4, 7, 7, 7, 7}}; + int[,] streams = { { 1, 1, 2, 2, 2, 2, 2 }, { 1, 1, 2, 3, 3, 3, 2 }, { 1, 4, 1, 3, 3, 5, 5 }, + { 4, 4, 3, 1, 3, 5, 5 }, { 4, 6, 6, 6, 7, 7, 5 }, { 6, 4, 6, 4, 5, 5, 7 }, + { 6, 6, 4, 7, 7, 7, 7 } }; // Note: This is 1-based - int[, ] placed = {{2, 1, 1}, {2, 3, 7}, {2, 5, 6}, {2, 7, 4}, {3, 2, 7}, - {3, 6, 1}, {4, 1, 4}, {4, 7, 5}, {5, 2, 2}, {5, 6, 6}}; + int[,] placed = { { 2, 1, 1 }, { 2, 3, 7 }, { 2, 5, 6 }, { 2, 7, 4 }, { 3, 2, 7 }, + { 3, 6, 1 }, { 4, 1, 4 }, { 4, 7, 5 }, { 5, 2, 2 }, { 5, 6, 6 } }; int n = streams.GetLength(0); int num_placed = placed.GetLength(0); @@ -48,7 +47,7 @@ public class Strimko2 { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n, "x"); IntVar[] x_flat = x.Flatten(); // @@ -85,17 +84,14 @@ public class Strimko2 { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write(x [i, j] - .Value() + - " "); + Console.Write(x[i, j].Value() + " "); } Console.WriteLine(); } @@ -110,5 +106,7 @@ public class Strimko2 { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/subset_sum.cs b/examples/contrib/subset_sum.cs index d08b4c8581..0803dcbe8f 100644 --- a/examples/contrib/subset_sum.cs +++ b/examples/contrib/subset_sum.cs @@ -71,17 +71,14 @@ public class SubsetSum { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(" s: {0}", s.Value()); } @@ -95,7 +92,7 @@ public class SubsetSum { } public static void Main(String[] args) { - int[] coins = {16, 17, 23, 24, 39, 40}; + int[] coins = { 16, 17, 23, 24, 39, 40 }; int total = 100; if (args.Length > 0) { diff --git a/examples/contrib/sudoku.cs b/examples/contrib/sudoku.cs index 1c6e8fcdf1..4a75644e00 100644 --- a/examples/contrib/sudoku.cs +++ b/examples/contrib/sudoku.cs @@ -38,17 +38,16 @@ public class Sudoku { IEnumerable RANGE = Enumerable.Range(0, n); // 0 marks an unknown value - int[, ] initial_grid = { - {0, 6, 0, 0, 5, 0, 0, 2, 0}, {0, 0, 0, 3, 0, 0, 0, 9, 0}, - {7, 0, 0, 6, 0, 0, 0, 1, 0}, {0, 0, 6, 0, 3, 0, 4, 0, 0}, - {0, 0, 4, 0, 7, 0, 1, 0, 0}, {0, 0, 5, 0, 9, 0, 8, 0, 0}, - {0, 4, 0, 0, 0, 1, 0, 0, 6}, {0, 3, 0, 0, 0, 8, 0, 0, 0}, - {0, 2, 0, 0, 4, 0, 0, 5, 0}}; + int[,] initial_grid = { { 0, 6, 0, 0, 5, 0, 0, 2, 0 }, { 0, 0, 0, 3, 0, 0, 0, 9, 0 }, + { 7, 0, 0, 6, 0, 0, 0, 1, 0 }, { 0, 0, 6, 0, 3, 0, 4, 0, 0 }, + { 0, 0, 4, 0, 7, 0, 1, 0, 0 }, { 0, 0, 5, 0, 9, 0, 8, 0, 0 }, + { 0, 4, 0, 0, 0, 1, 0, 0, 6 }, { 0, 3, 0, 0, 0, 8, 0, 0, 0 }, + { 0, 2, 0, 0, 4, 0, 0, 5, 0 } }; // // Decision variables // - IntVar[, ] grid = solver.MakeIntVarMatrix(n, n, 1, 9, "grid"); + IntVar[,] grid = solver.MakeIntVarMatrix(n, n, 1, 9, "grid"); IntVar[] grid_flat = grid.Flatten(); // @@ -75,26 +74,25 @@ public class Sudoku { // cells foreach (int i in CELL) { foreach (int j in CELL) { - solver.Add((from di in CELL from dj in CELL select - grid[i * cell_size + di, j * cell_size + dj]) - .ToArray() - .AllDifferent()); + solver.Add( + (from di in CELL from dj in CELL select grid[i * cell_size + di, j * cell_size + dj]) + .ToArray() + .AllDifferent()); } } // // Search // - DecisionBuilder db = solver.MakePhase(grid_flat, Solver.INT_VAR_SIMPLE, - Solver.INT_VALUE_SIMPLE); + DecisionBuilder db = + solver.MakePhase(grid_flat, Solver.INT_VAR_SIMPLE, Solver.INT_VALUE_SIMPLE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - Console.Write("{0} ", grid [i, j] - .Value()); + Console.Write("{0} ", grid[i, j].Value()); } Console.WriteLine(); } @@ -110,5 +108,7 @@ public class Sudoku { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/survo_puzzle.cs b/examples/contrib/survo_puzzle.cs index 3012e9b283..49fe5db3de 100644 --- a/examples/contrib/survo_puzzle.cs +++ b/examples/contrib/survo_puzzle.cs @@ -25,16 +25,16 @@ public class SurvoPuzzle { // static int default_r = 3; static int default_c = 4; - static int[] default_rowsums = {30, 18, 30}; - static int[] default_colsums = {27, 16, 10, 25}; - static int[, ] default_game = {{0, 6, 0, 0}, {8, 0, 0, 0}, {0, 0, 3, 0}}; + static int[] default_rowsums = { 30, 18, 30 }; + static int[] default_colsums = { 27, 16, 10, 25 }; + static int[,] default_game = { { 0, 6, 0, 0 }, { 8, 0, 0, 0 }, { 0, 0, 3, 0 } }; // for the actual problem static int r; static int c; static int[] rowsums; static int[] colsums; - static int[, ] game; + static int[,] game; /** * @@ -60,7 +60,7 @@ public class SurvoPuzzle { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(r, c, 1, r * c, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(r, c, 1, r * c, "x"); IntVar[] x_flat = x.Flatten(); // @@ -98,8 +98,7 @@ public class SurvoPuzzle { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_SIMPLE, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x_flat, Solver.INT_VAR_SIMPLE, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -109,8 +108,7 @@ public class SurvoPuzzle { Console.WriteLine("Solution #{0} ", sol + " "); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { - Console.Write("{0} ", x [i, j] - .Value()); + Console.Write("{0} ", x[i, j].Value()); } Console.WriteLine(); } diff --git a/examples/contrib/to_num.cs b/examples/contrib/to_num.cs index efd0389d9e..5de1debd35 100644 --- a/examples/contrib/to_num.cs +++ b/examples/contrib/to_num.cs @@ -29,7 +29,7 @@ public class ToNumTest { IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { - tmp[i] = (a[i] * (int) Math.Pow(bbase, (len - i - 1))).Var(); + tmp[i] = (a[i] * (int)Math.Pow(bbase, (len - i - 1))).Var(); } return tmp.Sum() == num; } @@ -50,7 +50,7 @@ public class ToNumTest { // Decision variables // IntVar[] x = solver.MakeIntVarArray(n, 0, bbase - 1, "x"); - IntVar num = solver.MakeIntVar(0, (int) Math.Pow(bbase, n) - 1, "num"); + IntVar num = solver.MakeIntVar(0, (int)Math.Pow(bbase, n) - 1, "num"); // // Constraints @@ -66,17 +66,14 @@ public class ToNumTest { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("\n" + num.Value() + ": "); for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } } @@ -88,5 +85,7 @@ public class ToNumTest { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/traffic_lights.cs b/examples/contrib/traffic_lights.cs index 894ace0759..9bb07551b3 100644 --- a/examples/contrib/traffic_lights.cs +++ b/examples/contrib/traffic_lights.cs @@ -75,13 +75,12 @@ public class TrafficLights { int g = 2; int y = 3; - string[] lights = {"r", "ry", "g", "y"}; + string[] lights = { "r", "ry", "g", "y" }; // The allowed combinations IntTupleSet allowed = new IntTupleSet(4); - allowed.InsertAll( - new long[][]{new long[]{r, r, g, g}, new long[]{ry, r, y, r}, - new long[]{g, g, r, r}, new long[]{y, r, ry, r}}); + allowed.InsertAll(new long[][] { new long[] { r, r, g, g }, new long[] { ry, r, y, r }, + new long[] { g, g, r, r }, new long[] { y, r, ry, r } }); // // Decision variables // @@ -100,27 +99,20 @@ public class TrafficLights { // for (int i = 0; i < n; i++) { int j = (1 + i) % n; - IntVar[] tmp = new IntVar[]{V[i], P[i], V[j], P[j]}; + IntVar[] tmp = new IntVar[] { V[i], P[i], V[j], P[j] }; solver.Add(tmp.AllowedAssignments(allowed)); } // // Search // - DecisionBuilder db = solver.MakePhase(VP, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(VP, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write("{0,2} {1,2} ", - lights [V [i] - .Value()] - , - lights [P [i] - .Value()] - ); + Console.Write("{0,2} {1,2} ", lights[V[i].Value()], lights[P[i].Value()]); } Console.WriteLine(); } @@ -133,5 +125,7 @@ public class TrafficLights { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/volsay.cs b/examples/contrib/volsay.cs index 0da8594b37..b9fa808bbd 100644 --- a/examples/contrib/volsay.cs +++ b/examples/contrib/volsay.cs @@ -27,8 +27,7 @@ public class Volsay { * Also see http://www.hakank.org/or-tools/volsay.py */ private static void Solve() { - Solver solver = new Solver( - "Volsay", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); + Solver solver = new Solver("Volsay", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); // // Variables @@ -50,11 +49,10 @@ public class Volsay { Console.WriteLine("Objective: {0}", solver.Objective().Value()); - Console.WriteLine("Gas : {0} ReducedCost: {1}", Gas.SolutionValue(), - Gas.ReducedCost()); + Console.WriteLine("Gas : {0} ReducedCost: {1}", Gas.SolutionValue(), Gas.ReducedCost()); - Console.WriteLine("Chloride : {0} ReducedCost: {1}", - Chloride.SolutionValue(), Chloride.ReducedCost()); + Console.WriteLine("Chloride : {0} ReducedCost: {1}", Chloride.SolutionValue(), + Chloride.ReducedCost()); double[] activities = solver.ComputeConstraintActivities(); Console.WriteLine("c1 : DualValue: {0} Activity: {1}", c1.DualValue(), @@ -67,5 +65,7 @@ public class Volsay { Console.WriteLine("Iterations: " + solver.Iterations()); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/volsay2.cs b/examples/contrib/volsay2.cs index 02584d94e9..cdff076a98 100644 --- a/examples/contrib/volsay2.cs +++ b/examples/contrib/volsay2.cs @@ -29,14 +29,13 @@ public class Volsay2 { * http://www.hakank.org/or-tools/volsay2.py */ private static void Solve() { - Solver solver = new Solver( - "Volsay2", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); + Solver solver = new Solver("Volsay2", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); int num_products = 2; IEnumerable PRODUCTS = Enumerable.Range(0, num_products); int Gas = 0; int Chloride = 1; - String[] products = {"Gas", "Chloride"}; + String[] products = { "Gas", "Chloride" }; // // Variables @@ -64,32 +63,22 @@ public class Volsay2 { } foreach (int p in PRODUCTS) { - Console.WriteLine("{0,-10}: {1} ReducedCost: {2}", products[p], - production [p] - .SolutionValue(), - production [p] - .ReducedCost()); + Console.WriteLine("{0,-10}: {1} ReducedCost: {2}", products[p], production[p].SolutionValue(), + production[p].ReducedCost()); } double[] activities = solver.ComputeConstraintActivities(); foreach (int c in CONSTRAINTS) { - Console.WriteLine( - "Constraint {0} DualValue {1} Activity: {2} lb: {3} ub: {4}", - c.ToString(), - cons [c] - .DualValue(), - activities [cons [c] - .Index()] - , - cons [c] - .Lb(), - cons [c] - .Ub()); + Console.WriteLine("Constraint {0} DualValue {1} Activity: {2} lb: {3} ub: {4}", c.ToString(), + cons[c].DualValue(), activities[cons[c].Index()], cons[c].Lb(), + cons[c].Ub()); } Console.WriteLine("\nWallTime: " + solver.WallTime()); Console.WriteLine("Iterations: " + solver.Iterations()); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/volsay3.cs b/examples/contrib/volsay3.cs index 6fef806d65..6a9bc33951 100644 --- a/examples/contrib/volsay3.cs +++ b/examples/contrib/volsay3.cs @@ -30,17 +30,16 @@ public class Volsay3 { * http://www.hakank.org/or-tools/volsay3.py */ private static void Solve() { - Solver solver = new Solver( - "Volsay3", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); + Solver solver = new Solver("Volsay3", Solver.OptimizationProblemType.CLP_LINEAR_PROGRAMMING); int num_products = 2; IEnumerable PRODUCTS = Enumerable.Range(0, num_products); - String[] products = {"Gas", "Chloride"}; - String[] components = {"nitrogen", "hydrogen", "chlorine"}; + String[] products = { "Gas", "Chloride" }; + String[] components = { "nitrogen", "hydrogen", "chlorine" }; - int[, ] demand = {{1, 3, 0}, {1, 4, 1}}; - int[] profit = {30, 40}; - int[] stock = {50, 180, 40}; + int[,] demand = { { 1, 3, 0 }, { 1, 4, 1 } }; + int[] profit = { 30, 40 }; + int[] stock = { 50, 180, 40 }; // // Variables @@ -56,17 +55,14 @@ public class Volsay3 { int c_len = components.Length; Constraint[] cons = new Constraint[c_len]; for (int c = 0; c < c_len; c++) { - cons[c] = - solver.Add((from p in PRODUCTS select(demand[p, c] * production[p])) - .ToArray() - .Sum() <= stock[c]); + cons[c] = solver.Add( + (from p in PRODUCTS select(demand[p, c] * production[p])).ToArray().Sum() <= stock[c]); } // // Objective // - solver.Maximize( - (from p in PRODUCTS select(profit[p] * production[p])).ToArray().Sum()); + solver.Maximize((from p in PRODUCTS select(profit[p] * production[p])).ToArray().Sum()); if (solver.Solve() != Solver.ResultStatus.OPTIMAL) { Console.WriteLine("The problem don't have an optimal solution."); @@ -75,31 +71,22 @@ public class Volsay3 { Console.WriteLine("Objective: {0}", solver.Objective().Value()); foreach (int p in PRODUCTS) { - Console.WriteLine("{0,-10}: {1} ReducedCost: {2}", products[p], - production [p] - .SolutionValue(), - production [p] - .ReducedCost()); + Console.WriteLine("{0,-10}: {1} ReducedCost: {2}", products[p], production[p].SolutionValue(), + production[p].ReducedCost()); } double[] activities = solver.ComputeConstraintActivities(); for (int c = 0; c < c_len; c++) { - Console.WriteLine( - "Constraint {0} DualValue {1} Activity: {2} lb: {3} ub: {4}", c, - cons [c] - .DualValue(), - activities [cons [c] - .Index()] - , - cons [c] - .Lb(), - cons [c] - .Ub()); + Console.WriteLine("Constraint {0} DualValue {1} Activity: {2} lb: {3} ub: {4}", c, + cons[c].DualValue(), activities[cons[c].Index()], cons[c].Lb(), + cons[c].Ub()); } Console.WriteLine("\nWallTime: " + solver.WallTime()); Console.WriteLine("Iterations: " + solver.Iterations()); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/wedding_optimal_chart.cs b/examples/contrib/wedding_optimal_chart.cs index 6a94245a92..8e488317b0 100644 --- a/examples/contrib/wedding_optimal_chart.cs +++ b/examples/contrib/wedding_optimal_chart.cs @@ -89,30 +89,29 @@ public class WeddingOptimalChart { // Connection matrix: who knows who, and how strong // is the relation - int[, ] C = {{1, 50, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {50, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 1, 50, 1, 1, 1, 1, 10, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 50, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 1, 1, 1, 50, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 1, 1, 50, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 1, 1, 1, 1, 1, 50, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 1, 1, 1, 1, 50, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1, 10, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 50, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}, - {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1}}; + int[,] C = { { 1, 50, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 50, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 1, 50, 1, 1, 1, 1, 10, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 50, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 1, 1, 1, 50, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 1, 1, 50, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 1, 1, 1, 1, 1, 50, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 1, 1, 1, 1, 50, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 1, 1, 10, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 50, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }, + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 } }; // Names of the guests. B: Bride side, G: Groom side - String[] names = { - "Deb (B)", "John (B)", "Martha (B)", "Travis (B)", "Allan (B)", - "Lois (B)", "Jayne (B)", "Brad (B)", "Abby (B)", "Mary Helen (G)", - "Lee (G)", "Annika (G)", "Carl (G)", "Colin (G)", "Shirley (G)", - "DeAnn (G)", "Lori (G)"}; + String[] names = { "Deb (B)", "John (B)", "Martha (B)", "Travis (B)", "Allan (B)", + "Lois (B)", "Jayne (B)", "Brad (B)", "Abby (B)", "Mary Helen (G)", + "Lee (G)", "Annika (G)", "Carl (G)", "Colin (G)", "Shirley (G)", + "DeAnn (G)", "Lori (G)" }; int m = C.GetLength(0); // number of quests @@ -153,25 +152,21 @@ public class WeddingOptimalChart { // // Search // - DecisionBuilder db = solver.MakePhase(tables, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = solver.MakePhase(tables, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("z: {0}", z.Value()); Console.Write("Table: "); foreach (int j in MRANGE) { - Console.Write(tables [j] - .Value() + - " "); + Console.Write(tables[j].Value() + " "); } Console.WriteLine(); foreach (int i in NRANGE) { Console.Write("Table {0}: ", i); foreach (int j in MRANGE) { - if (tables [j] - .Value() == i) { + if (tables[j].Value() == i) { Console.Write(names[j] + " "); } } @@ -188,5 +183,7 @@ public class WeddingOptimalChart { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/who_killed_agatha.cs b/examples/contrib/who_killed_agatha.cs index e0ae38fecc..7baddc9cb0 100644 --- a/examples/contrib/who_killed_agatha.cs +++ b/examples/contrib/who_killed_agatha.cs @@ -38,9 +38,9 @@ public class WhoKilledAgatha { // IntVar the_killer = solver.MakeIntVar(0, 2, "the_killer"); IntVar the_victim = solver.MakeIntVar(0, 2, "the_victim"); - IntVar[, ] hates = solver.MakeIntVarMatrix(n, n, 0, 1, "hates"); + IntVar[,] hates = solver.MakeIntVarMatrix(n, n, 0, 1, "hates"); IntVar[] hates_flat = hates.Flatten(); - IntVar[, ] richer = solver.MakeIntVarMatrix(n, n, 0, 1, "richer"); + IntVar[,] richer = solver.MakeIntVarMatrix(n, n, 0, 1, "richer"); IntVar[] richer_flat = richer.Flatten(); IntVar[] all = new IntVar[2 * n * n]; // for branching @@ -111,9 +111,7 @@ public class WhoKilledAgatha { // forall i in 0..2: // (sum j in 0..2: hates[i,j]) <= 2 for (int i = 0; i < n; i++) { - solver.Add((from j in Enumerable.Range(0, n) select hates[i, j]) - .ToArray() - .Sum() <= 2); + solver.Add((from j in Enumerable.Range(0, n) select hates[i, j]).ToArray().Sum() <= 2); } // Who killed Agatha? @@ -122,8 +120,8 @@ public class WhoKilledAgatha { // // Search // - DecisionBuilder db = solver.MakePhase(all, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(all, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -139,5 +137,7 @@ public class WhoKilledAgatha { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/word_square.cs b/examples/contrib/word_square.cs index 9655d3dd75..141088423b 100644 --- a/examples/contrib/word_square.cs +++ b/examples/contrib/word_square.cs @@ -64,8 +64,7 @@ public class WordSquare { // // Decision variables // - IntVar[, ] A = - solver.MakeIntVarMatrix(num_words, word_len, 0, num_letters, "A"); + IntVar[,] A = solver.MakeIntVarMatrix(num_words, word_len, 0, num_letters, "A"); IntVar[] A_flat = A.Flatten(); IntVar[] E = solver.MakeIntVarArray(n, 0, num_words, "E"); @@ -76,27 +75,24 @@ public class WordSquare { // copy the words to a matrix for (int i = 0; i < num_words; i++) { - char[] s = words [i] - .ToArray(); + char[] s = words[i].ToArray(); foreach (int j in WORDLEN) { - int t = (int) d[s[j]]; + int t = (int)d[s[j]]; solver.Add(A[i, j] == t); } } foreach (int i in WORDLEN) { foreach (int j in WORDLEN) { - solver.Add(A_flat.Element(E[i] * word_len + j) == - A_flat.Element(E[j] * word_len + i)); + solver.Add(A_flat.Element(E[i] * word_len + j) == A_flat.Element(E[j] * word_len + i)); } } // // Search // - DecisionBuilder db = - solver.MakePhase(E.Concat(A_flat).ToArray(), - Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(E.Concat(A_flat).ToArray(), Solver.CHOOSE_FIRST_UNBOUND, + Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); @@ -104,9 +100,7 @@ public class WordSquare { while (solver.NextSolution()) { num_sols++; for (int i = 0; i < n; i++) { - Console.WriteLine(words [E [i] - .Value()] - + " "); + Console.WriteLine(words[E[i].Value()] + " "); } Console.WriteLine(); @@ -139,8 +133,8 @@ public class WordSquare { while ((str = inr.ReadLine()) != null) { str = str.Trim().ToLower(); // skip weird words - if (Regex.Match(str, @"[^a-z]").Success || d.Contains(str) || - str.Length == 0 || str.Length != word_len) { + if (Regex.Match(str, @"[^a-z]").Success || d.Contains(str) || str.Length == 0 || + str.Length != word_len) { continue; } diff --git a/examples/contrib/xkcd.cs b/examples/contrib/xkcd.cs index 4b19b7857c..3fd6e51531 100644 --- a/examples/contrib/xkcd.cs +++ b/examples/contrib/xkcd.cs @@ -31,7 +31,7 @@ public class Xkcd { // int n = 6; // for price and total: multiplied by 100 to be able to use integers - int[] price = {215, 275, 335, 355, 420, 580}; + int[] price = { 215, 275, 335, 355, 420, 580 }; int total = 1505; // @@ -47,15 +47,12 @@ public class Xkcd { // // Search // - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { for (int i = 0; i < n; i++) { - Console.Write(x [i] - .Value() + - " "); + Console.Write(x[i].Value() + " "); } Console.WriteLine(); } @@ -68,5 +65,7 @@ public class Xkcd { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/contrib/young_tableaux.cs b/examples/contrib/young_tableaux.cs index a6cc00fd53..bdab9712bb 100644 --- a/examples/contrib/young_tableaux.cs +++ b/examples/contrib/young_tableaux.cs @@ -37,7 +37,7 @@ public class YoungTableaux { // // Decision variables // - IntVar[, ] x = solver.MakeIntVarMatrix(n, n, 1, n + 1, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(n, n, 1, n + 1, "x"); IntVar[] x_flat = x.Flatten(); // partition structure @@ -85,30 +85,26 @@ public class YoungTableaux { // // Search // - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("p: "); for (int i = 0; i < n; i++) { - Console.Write(p [i] - .Value() + - " "); + Console.Write(p[i].Value() + " "); } Console.WriteLine("\nx:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - long val = x [i, j] - .Value(); + long val = x[i, j].Value(); if (val <= n) { Console.Write(val + " "); } } - if (p [i] - .Value() > 0) { + if (p[i].Value() > 0) { Console.WriteLine(); } } diff --git a/examples/contrib/zebra.cs b/examples/contrib/zebra.cs index 48fcdc30d7..bf1207c240 100644 --- a/examples/contrib/zebra.cs +++ b/examples/contrib/zebra.cs @@ -94,28 +94,24 @@ public class NQueens { IntVar parliaments = solver.MakeIntVar(1, n, "parliaments"); // for search - IntVar[] all_vars = { - parliaments, kools, chesterfields, lucky_strike, old_gold, - englishman, spaniard, japanese, ukrainian, norwegian, - dog, snails, fox, zebra, horse, - tea, coffee, water, milk, fruit_juice, - red, green, yellow, blue, ivory}; + IntVar[] all_vars = { parliaments, kools, chesterfields, lucky_strike, old_gold, + englishman, spaniard, japanese, ukrainian, norwegian, + dog, snails, fox, zebra, horse, + tea, coffee, water, milk, fruit_juice, + red, green, yellow, blue, ivory }; // // Constraints // // Alldifferents - solver.Add(new IntVar[]{red, green, yellow, blue, ivory}.AllDifferent()); + solver.Add(new IntVar[] { red, green, yellow, blue, ivory }.AllDifferent()); solver.Add( - new IntVar[]{englishman, spaniard, japanese, ukrainian, norwegian} - .AllDifferent()); - solver.Add(new IntVar[]{dog, snails, fox, zebra, horse}.AllDifferent()); + new IntVar[] { englishman, spaniard, japanese, ukrainian, norwegian }.AllDifferent()); + solver.Add(new IntVar[] { dog, snails, fox, zebra, horse }.AllDifferent()); + solver.Add(new IntVar[] { tea, coffee, water, milk, fruit_juice }.AllDifferent()); solver.Add( - new IntVar[]{tea, coffee, water, milk, fruit_juice}.AllDifferent()); - solver.Add( - new IntVar[]{parliaments, kools, chesterfields, lucky_strike, old_gold} - .AllDifferent()); + new IntVar[] { parliaments, kools, chesterfields, lucky_strike, old_gold }.AllDifferent()); // // The clues @@ -138,13 +134,13 @@ public class NQueens { // // Search // - DecisionBuilder db = solver.MakePhase(all_vars, Solver.INT_VAR_DEFAULT, - Solver.INT_VALUE_DEFAULT); + DecisionBuilder db = + solver.MakePhase(all_vars, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT); solver.NewSearch(db); - IntVar[] p = {englishman, spaniard, japanese, ukrainian, norwegian}; - int[] ix = {0, 1, 2, 3, 4}; + IntVar[] p = { englishman, spaniard, japanese, ukrainian, norwegian }; + int[] ix = { 0, 1, 2, 3, 4 }; while (solver.NextSolution()) { int water_drinker = (from i in ix where p [i] .Value() == water.Value() select i) @@ -152,10 +148,8 @@ public class NQueens { int zebra_owner = (from i in ix where p [i] .Value() == zebra.Value() select i) .First(); - Console.WriteLine("The {0} drinks water.", p [water_drinker] - .ToString()); - Console.WriteLine("The {0} owns the zebra", p [zebra_owner] - .ToString()); + Console.WriteLine("The {0} drinks water.", p[water_drinker].ToString()); + Console.WriteLine("The {0} owns the zebra", p[zebra_owner].ToString()); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); @@ -166,5 +160,7 @@ public class NQueens { solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/dotnet/BalanceGroupSat.cs b/examples/dotnet/BalanceGroupSat.cs index fa717501e4..798db7a4be 100644 --- a/examples/dotnet/BalanceGroupSat.cs +++ b/examples/dotnet/BalanceGroupSat.cs @@ -46,13 +46,11 @@ public class BalanceGroupSat { itemsPerColor[color] = new List(); foreach (var item in allItems) { if (colors[item] == color) - itemsPerColor [color] - .Add(item); + itemsPerColor[color].Add(item); } } - Console.WriteLine( - $"Model has {numberItems}, {numberGroups} groups and {numberColors} colors"); + Console.WriteLine($"Model has {numberItems}, {numberGroups} groups and {numberColors} colors"); Console.WriteLine($" Average sum per group = {averageSumPerGroup}"); var model = new CpModel(); @@ -60,16 +58,14 @@ public class BalanceGroupSat { var itemInGroup = new IntVar[numberItems, numberGroups]; foreach (var item in allItems) { foreach (var @group in allGroups) { - itemInGroup[item, @group] = - model.NewBoolVar($"item {item} in group {@group}"); + itemInGroup[item, @group] = model.NewBoolVar($"item {item} in group {@group}"); } } // Each group must have the same size. foreach (var @group in allGroups) { var itemsInGroup = allItems.Select(x => itemInGroup[x, @group]).ToArray(); - model.AddLinearConstraint(LinearExpr.Sum(itemsInGroup), numItemsPerGroup, - numItemsPerGroup); + model.AddLinearConstraint(LinearExpr.Sum(itemsInGroup), numItemsPerGroup, numItemsPerGroup); } //# One item must belong to exactly one group. @@ -95,16 +91,14 @@ public class BalanceGroupSat { var colorInGroup = new IntVar[numberColors, numberGroups]; foreach (var @group in allGroups) { foreach (var color in allColors) { - colorInGroup[color, @group] = - model.NewBoolVar($"color {color} is in group {@group}"); + colorInGroup[color, @group] = model.NewBoolVar($"color {color} is in group {@group}"); } } // Item is in a group implies its color is in that group. foreach (var item in allItems) { foreach (var @group in allGroups) { - model.AddImplication(itemInGroup[item, @group], - colorInGroup[colors[item], @group]); + model.AddImplication(itemInGroup[item, @group], colorInGroup[colors[item], @group]); } } @@ -113,11 +107,8 @@ public class BalanceGroupSat { foreach (var color in allColors) { foreach (var @group in allGroups) { var literal = colorInGroup[color, @group]; - var items = itemsPerColor [color] - .Select(x => itemInGroup[x, @group]) - .ToArray(); - model.Add(LinearExpr.Sum(items) >= minItemsOfSameColorPerGroup) - .OnlyEnforceIf(literal); + var items = itemsPerColor[color].Select(x => itemInGroup[x, @group]).ToArray(); + model.Add(LinearExpr.Sum(items) >= minItemsOfSameColorPerGroup).OnlyEnforceIf(literal); } } @@ -138,8 +129,7 @@ public class BalanceGroupSat { var solver = new CpSolver(); solver.StringParameters = ""; - var solutionPrinter = - new SolutionPrinter(values, colors, allGroups, allItems, itemInGroup); + var solutionPrinter = new SolutionPrinter(values, colors, allGroups, allItems, itemInGroup); var status = solver.SolveWithSolutionCallback(model, solutionPrinter); } @@ -149,12 +139,12 @@ public class BalanceGroupSat { private int[] _colors; private int[] _allGroups; private int[] _allItems; - private IntVar[, ] _itemInGroup; + private IntVar[,] _itemInGroup; private int _solutionCount; - public SolutionPrinter(int[] values, int[] colors, int[] allGroups, - int[] allItems, IntVar[, ] itemInGroup) { + public SolutionPrinter(int[] values, int[] colors, int[] allGroups, int[] allItems, + IntVar[,] itemInGroup) { this._values = values; this._colors = colors; this._allGroups = allGroups; @@ -175,8 +165,7 @@ public class BalanceGroupSat { groups[@group] = new List(); foreach (var item in _allItems) { if (BooleanValue(_itemInGroup[item, @group])) { - groups [@group] - .Add(item); + groups[@group].Add(item); sum[@group] += _values[item]; } } diff --git a/examples/dotnet/GateSchedulingSat.cs b/examples/dotnet/GateSchedulingSat.cs index 3b72dc739e..3cb6eec97c 100644 --- a/examples/dotnet/GateSchedulingSat.cs +++ b/examples/dotnet/GateSchedulingSat.cs @@ -30,9 +30,9 @@ public class GateSchedulingSat { static void Main() { CpModel model = new CpModel(); - int[, ] jobs = - new[, ]{{3, 3}, {2, 5}, {1, 3}, {3, 7}, {7, 3}, {2, 2}, {2, 2}, {5, 5}, - {10, 2}, {4, 3}, {2, 6}, {1, 2}, {6, 8}, {4, 5}, {3, 7}}; + int[,] jobs = + new[,] { { 3, 3 }, { 2, 5 }, { 1, 3 }, { 3, 7 }, { 7, 3 }, { 2, 2 }, { 2, 2 }, { 5, 5 }, + { 10, 2 }, { 4, 3 }, { 2, 6 }, { 1, 2 }, { 6, 8 }, { 4, 5 }, { 3, 7 } }; int max_length = 10; int num_jobs = jobs.GetLength(0); @@ -56,35 +56,28 @@ public class GateSchedulingSat { IntVar start = model.NewIntVar(0, horizon, String.Format("start_{0}", i)); int duration = jobs[i, 0]; IntVar end = model.NewIntVar(0, horizon, String.Format("end_{0}", i)); - IntervalVar interval = model.NewIntervalVar( - start, duration, end, String.Format("interval_{0}", i)); + IntervalVar interval = + model.NewIntervalVar(start, duration, end, String.Format("interval_{0}", i)); starts.Add(start); intervals.Add(interval); ends.Add(end); demands.Add(jobs[i, 1]); - IntVar performed_on_m0 = - model.NewBoolVar(String.Format("perform_{0}_on_m0", i)); + IntVar performed_on_m0 = model.NewBoolVar(String.Format("perform_{0}_on_m0", i)); performed.Add(performed_on_m0); // Create an optional copy of interval to be executed on machine 0. - IntVar start0 = - model.NewIntVar(0, horizon, String.Format("start_{0}_on_m0", i)); - IntVar end0 = - model.NewIntVar(0, horizon, String.Format("end_{0}_on_m0", i)); - IntervalVar interval0 = - model.NewOptionalIntervalVar(start0, duration, end0, performed_on_m0, - String.Format("interval_{0}_on_m0", i)); + IntVar start0 = model.NewIntVar(0, horizon, String.Format("start_{0}_on_m0", i)); + IntVar end0 = model.NewIntVar(0, horizon, String.Format("end_{0}_on_m0", i)); + IntervalVar interval0 = model.NewOptionalIntervalVar(start0, duration, end0, performed_on_m0, + String.Format("interval_{0}_on_m0", i)); intervals0.Add(interval0); // Create an optional copy of interval to be executed on machine 1. - IntVar start1 = - model.NewIntVar(0, horizon, String.Format("start_{0}_on_m1", i)); - IntVar end1 = - model.NewIntVar(0, horizon, String.Format("end_{0}_on_m1", i)); + IntVar start1 = model.NewIntVar(0, horizon, String.Format("start_{0}_on_m1", i)); + IntVar end1 = model.NewIntVar(0, horizon, String.Format("end_{0}_on_m1", i)); IntervalVar interval1 = model.NewOptionalIntervalVar( - start1, duration, end1, performed_on_m0.Not(), - String.Format("interval_{0}_on_m1", i)); + start1, duration, end1, performed_on_m0.Not(), String.Format("interval_{0}_on_m1", i)); intervals1.Add(interval1); // We only propagate the constraint if the tasks is performed on the @@ -119,8 +112,7 @@ public class GateSchedulingSat { long performed_machine = 1 - solver.Value(performed[i]); long start = solver.Value(starts[i]); Console.WriteLine( - String.Format(" - Job {0} starts at {1} on machine {2}", i, start, - performed_machine)); + String.Format(" - Job {0} starts at {1} on machine {2}", i, start, performed_machine)); } Console.WriteLine("Statistics"); Console.WriteLine(" - conflicts : " + solver.NumConflicts()); diff --git a/examples/dotnet/JobshopFt06Sat.cs b/examples/dotnet/JobshopFt06Sat.cs index c3accfe756..0976a72eb2 100644 --- a/examples/dotnet/JobshopFt06Sat.cs +++ b/examples/dotnet/JobshopFt06Sat.cs @@ -30,12 +30,12 @@ public class JobshopFt06Sat { } static void Main() { - int[, ] durations = new int[, ]{{1, 3, 6, 7, 3, 6}, {8, 5, 10, 10, 10, 4}, - {5, 4, 8, 9, 1, 7}, {5, 5, 5, 3, 8, 9}, - {9, 3, 5, 4, 3, 1}, {3, 3, 9, 10, 4, 1}}; - int[, ] machines = - new int[, ]{{2, 0, 1, 3, 5, 4}, {1, 2, 4, 5, 0, 3}, {2, 3, 5, 0, 1, 4}, - {1, 0, 2, 3, 4, 5}, {2, 1, 4, 5, 0, 3}, {1, 3, 5, 0, 4, 2}}; + int[,] durations = + new int[,] { { 1, 3, 6, 7, 3, 6 }, { 8, 5, 10, 10, 10, 4 }, { 5, 4, 8, 9, 1, 7 }, + { 5, 5, 5, 3, 8, 9 }, { 9, 3, 5, 4, 3, 1 }, { 3, 3, 9, 10, 4, 1 } }; + int[,] machines = + new int[,] { { 2, 0, 1, 3, 5, 4 }, { 1, 2, 4, 5, 0, 3 }, { 2, 3, 5, 0, 1, 4 }, + { 1, 0, 2, 3, 4, 5 }, { 2, 1, 4, 5, 0, 3 }, { 1, 3, 5, 0, 4, 2 } }; int num_jobs = durations.GetLength(0); int num_machines = durations.GetLength(1); @@ -53,23 +53,20 @@ public class JobshopFt06Sat { CpModel model = new CpModel(); // Creates jobs. - Task[, ] all_tasks = new Task[num_jobs, num_machines]; + Task[,] all_tasks = new Task[num_jobs, num_machines]; foreach (int j in all_jobs) { foreach (int m in all_machines) { - IntVar start_var = - model.NewIntVar(0, horizon, String.Format("start_{0}_{1}", j, m)); + IntVar start_var = model.NewIntVar(0, horizon, String.Format("start_{0}_{1}", j, m)); int duration = durations[j, m]; - IntVar end_var = - model.NewIntVar(0, horizon, String.Format("end_{0}_{1}", j, m)); - IntervalVar interval_var = - model.NewIntervalVar(start_var, duration, end_var, - String.Format("interval_{0}_{1}", j, m)); + IntVar end_var = model.NewIntVar(0, horizon, String.Format("end_{0}_{1}", j, m)); + IntervalVar interval_var = model.NewIntervalVar(start_var, duration, end_var, + String.Format("interval_{0}_{1}", j, m)); all_tasks[j, m] = new Task(start_var, end_var, interval_var); } } // Create disjuctive constraints. - List[] machine_to_jobs = new List[ num_machines ]; + List[] machine_to_jobs = new List[num_machines]; foreach (int m in all_machines) { machine_to_jobs[m] = new List(); } diff --git a/examples/dotnet/JobshopSat.cs b/examples/dotnet/JobshopSat.cs index e51269e0b2..dd543e1721 100644 --- a/examples/dotnet/JobshopSat.cs +++ b/examples/dotnet/JobshopSat.cs @@ -11,22 +11,10 @@ class Task { Machine = machine; Name = "T" + taskId + "J" + jobId + "M" + machine + "D" + duration; } - public int TaskId { - get; - set; - } - public int JobId { - get; - set; - } - public int Machine { - get; - set; - } - public int Duration { - get; - set; - } + public int TaskId { get; set; } + public int JobId { get; set; } + public int Machine { get; set; } + public int Duration { get; set; } public string Name { get; } } @@ -106,15 +94,13 @@ class JobshopSat { // ----- Creates all intervals and integer variables ----- // Stores all tasks attached interval variables per job. - List> jobsToTasks = - new List>(jobsCount); + List> jobsToTasks = new List>(jobsCount); List> jobsToStarts = new List>(jobsCount); List> jobsToEnds = new List>(jobsCount); // machinesToTasks stores the same interval variables as above, but // grouped my machines instead of grouped by jobs. - List> machinesToTasks = - new List>(machinesCount); + List> machinesToTasks = new List>(machinesCount); List> machinesToStarts = new List>(machinesCount); for (int i = 0; i < machinesCount; i++) { machinesToTasks.Add(new List()); @@ -129,18 +115,12 @@ class JobshopSat { foreach (Task task in job) { IntVar start = model.NewIntVar(0, horizon, task.Name); IntVar end = model.NewIntVar(0, horizon, task.Name); - IntervalVar oneTask = - model.NewIntervalVar(start, task.Duration, end, task.Name); - jobsToTasks [task.JobId] - .Add(oneTask); - jobsToStarts [task.JobId] - .Add(start); - jobsToEnds [task.JobId] - .Add(end); - machinesToTasks [task.Machine] - .Add(oneTask); - machinesToStarts [task.Machine] - .Add(start); + IntervalVar oneTask = model.NewIntervalVar(start, task.Duration, end, task.Name); + jobsToTasks[task.JobId].Add(oneTask); + jobsToStarts[task.JobId].Add(start); + jobsToEnds[task.JobId].Add(end); + machinesToTasks[task.Machine].Add(oneTask); + machinesToStarts[task.Machine].Add(start); } } @@ -149,9 +129,7 @@ class JobshopSat { // Creates precedences inside jobs. for (int j = 0; j < jobsToTasks.Count; ++j) { for (int t = 0; t < jobsToTasks[j].Count - 1; ++t) { - model.Add(jobsToEnds [j] - [t] <= jobsToStarts [j] - [t + 1]); + model.Add(jobsToEnds[j][t] <= jobsToStarts[j][t + 1]); } } @@ -163,8 +141,7 @@ class JobshopSat { // Creates array of end_times of jobs. IntVar[] allEnds = new IntVar[jobsCount]; for (int i = 0; i < jobsCount; i++) { - allEnds[i] = jobsToEnds [i] - .Last(); + allEnds[i] = jobsToEnds[i].Last(); } // Objective: minimize the makespan (maximum end times of all tasks) @@ -186,8 +163,7 @@ class JobshopSat { Console.WriteLine("Makespan = " + solver.ObjectiveValue); for (int m = 0; m < machinesCount; ++m) { Console.WriteLine($"Machine {m}:"); - SortedDictionary starts = - new SortedDictionary(); + SortedDictionary starts = new SortedDictionary(); foreach (IntVar var in machinesToStarts[m]) { starts[solver.Value(var)] = var.Name(); } diff --git a/examples/dotnet/NetworkRoutingSat.cs b/examples/dotnet/NetworkRoutingSat.cs index fa21416b21..079ef5bc50 100644 --- a/examples/dotnet/NetworkRoutingSat.cs +++ b/examples/dotnet/NetworkRoutingSat.cs @@ -32,9 +32,8 @@ using System.Linq; /// A random problem generator is also included. /// public class NetworkRoutingSat { - private static int clients = - 0; // Number of network clients nodes. If equal to zero, then all - // backbones nodes are also client nodes. + private static int clients = 0; // Number of network clients nodes. If equal to zero, then all + // backbones nodes are also client nodes. private static int backbones = 0; // "Number of backbone nodes" private static int demands = 0; // "Number of network demands." private static int trafficMin = 0; // "Min traffic of a demand." @@ -46,21 +45,16 @@ public class NetworkRoutingSat { private static int minBackboneDegree = 0; //"Min number of connections from a backbone node to the rest of the // backbone nodes." - private static int maxBackboneDegree = - 0; // "Max number of connections from a backbone node to the rest of the - // backbone nodes." - private static int maxCapacity = 0; //"Max traffic on any arc." - private static int fixedChargeCost = - 0; //"Fixed charged cost when using an arc." - private static int seed = 0; //"Random seed" - private static double comfortZone = - 0.85; // "Above this limit in 1/1000th, the link is said to be - // congested." - private static int extraHops = - 6; // "When creating all paths for a demand, we look at paths with - // maximum length 'shortest path + extra_hops'" - private static int maxPaths = - 1200; //"Max number of possible paths for a demand." + private static int maxBackboneDegree = 0; // "Max number of connections from a backbone node to + // the rest of the backbone nodes." + private static int maxCapacity = 0; //"Max traffic on any arc." + private static int fixedChargeCost = 0; //"Fixed charged cost when using an arc." + private static int seed = 0; //"Random seed" + private static double comfortZone = 0.85; // "Above this limit in 1/1000th, the link is said to + // be congested." + private static int extraHops = 6; // "When creating all paths for a demand, we look at paths with + // maximum length 'shortest path + extra_hops'" + private static int maxPaths = 1200; //"Max number of possible paths for a demand." private static bool printModel = false; //"Print details of the model." private static string parameters = ""; // "Sat parameters." @@ -70,9 +64,8 @@ public class NetworkRoutingSat { readArgs(args); var builder = new NetworkRoutingDataBuilder(); var data = builder.BuildModelFromParameters( - clients, backbones, demands, trafficMin, trafficMax, minClientDegree, - maxClientDegree, minBackboneDegree, maxBackboneDegree, maxCapacity, - fixedChargeCost, seed); + clients, backbones, demands, trafficMin, trafficMax, minClientDegree, maxClientDegree, + minBackboneDegree, maxBackboneDegree, maxCapacity, fixedChargeCost, seed); var solver = new NetworkRoutingSolver(); solver.Init(data, extraHops, maxPaths); var cost = solver.Solve(); @@ -99,8 +92,7 @@ public class NetworkRoutingSat { readString(args, ref parameters, nameof(parameters)); } - private static void readDouble(string[] args, ref double setting, - string arg) { + private static void readDouble(string[] args, ref double setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = Convert.ToDouble(v.Value); @@ -121,16 +113,14 @@ public class NetworkRoutingSat { } } - private static void readString(string[] args, ref string setting, - string arg) { + private static void readString(string[] args, ref string setting, string arg) { var v = getArgValue(args, arg); if (v.IsSet) { setting = v.Value; } } - private static(bool IsSet, string Value) - getArgValue(string[] args, string arg) { + private static (bool IsSet, string Value) getArgValue(string[] args, string arg) { string lookup = $"--{arg}="; var item = args.FirstOrDefault(x => x.StartsWith(lookup)); @@ -153,11 +143,7 @@ public class NetworkRoutingSat { private Dictionary<(int node1, int node2), int> _demands = new Dictionary<(int node1, int node2), int>(); - public int NumberOfNodes { - get; - set; - } - = -1; + public int NumberOfNodes { get; set; } = -1; public int NumberOfArcs { get { return _arcs.Count(); } @@ -167,25 +153,14 @@ public class NetworkRoutingSat { get { return _demands.Count(); } } - public int MaximumCapacity { - get; - set; - } - = -1; - public int FixedChargeCost { - get; - set; - } - = -1; - public string Name { - get; - set; - } - = string.Empty; + public int MaximumCapacity { get; set; } = -1; + public int FixedChargeCost { get; set; } = -1; + public string Name { get; set; } = string.Empty; public void AddDemand(int source, int destination, int traffic) { var pair = (source, destination); - if (!_demands.ContainsKey(pair)) _demands.Add(pair, traffic); + if (!_demands.ContainsKey(pair)) + _demands.Add(pair, traffic); } public void AddArc(int node1, int node2, int capacity) { @@ -194,14 +169,16 @@ public class NetworkRoutingSat { public int Demand(int source, int destination) { var pair = (source, destination); - if (_demands.TryGetValue(pair, out var demand)) return demand; + if (_demands.TryGetValue(pair, out var demand)) + return demand; return 0; } public int Capacity(int node1, int node2) { var pair = (Math.Min(node1, node2), Math.Max(node1, node2)); - if (_arcs.TryGetValue(pair, out var capacity)) return capacity; + if (_arcs.TryGetValue(pair, out var capacity)) + return capacity; return 0; } @@ -225,16 +202,17 @@ public class NetworkRoutingSat { private List _degrees; private Random _random; - public NetworkRoutingData BuildModelFromParameters( - int numClients, int numBackbones, int numDemands, int trafficMin, - int trafficMax, int minClientDegree, int maxClientDegree, - int minBackboneDegree, int maxBackboneDegree, int maxCapacity, - int fixedChargeCost, int seed) { + public NetworkRoutingData BuildModelFromParameters(int numClients, int numBackbones, + int numDemands, int trafficMin, + int trafficMax, int minClientDegree, + int maxClientDegree, int minBackboneDegree, + int maxBackboneDegree, int maxCapacity, + int fixedChargeCost, int seed) { Debug.Assert(numBackbones >= 1); Debug.Assert(numClients >= 0); Debug.Assert(numDemands >= 1); - Debug.Assert(numDemands <= (numClients == 0 ? numBackbones * numBackbones - : numClients * numBackbones)); + Debug.Assert(numDemands <= + (numClients == 0 ? numBackbones * numBackbones : numClients * numBackbones)); Debug.Assert(maxClientDegree >= minClientDegree); Debug.Assert(maxBackboneDegree >= minBackboneDegree); Debug.Assert(trafficMax >= 1); @@ -248,14 +226,13 @@ public class NetworkRoutingSat { int size = numBackbones + numClients; initData(size, seed); - buildGraph(numClients, numBackbones, minClientDegree, maxClientDegree, - minBackboneDegree, maxBackboneDegree); + buildGraph(numClients, numBackbones, minClientDegree, maxClientDegree, minBackboneDegree, + maxBackboneDegree); NetworkRoutingData data = new NetworkRoutingData(); - createDemands(numClients, numBackbones, numDemands, trafficMin, - trafficMax, data); - fillData(numClients, numBackbones, numDemands, trafficMin, trafficMax, - minClientDegree, maxClientDegree, minBackboneDegree, - maxBackboneDegree, maxCapacity, fixedChargeCost, seed, data); + createDemands(numClients, numBackbones, numDemands, trafficMin, trafficMax, data); + fillData(numClients, numBackbones, numDemands, trafficMin, trafficMax, minClientDegree, + maxClientDegree, minBackboneDegree, maxBackboneDegree, maxCapacity, fixedChargeCost, + seed, data); return data; } @@ -265,8 +242,7 @@ public class NetworkRoutingSat { for (int i = 0; i < size; i++) { _network.Add(new List(size)); for (int j = 0; j < size; j++) { - _network [i] - .Add(false); + _network[i].Add(false); } } @@ -278,9 +254,8 @@ public class NetworkRoutingSat { _random = new Random(seed); } - private void buildGraph(int numClients, int numBackbones, - int minClientDegree, int maxClientDegree, - int minBackboneDegree, int maxBackboneDegree) { + private void buildGraph(int numClients, int numBackbones, int minClientDegree, + int maxClientDegree, int minBackboneDegree, int maxBackboneDegree) { int size = numBackbones + numClients; for (int i = 1; i < numBackbones; i++) { int j = randomUniform(i); @@ -334,8 +309,7 @@ public class NetworkRoutingSat { while (_degrees[i] < degree) { int j = randomUniform(numBackbones); - if (!_network [i] - [j]) { + if (!_network[i][j]) { addEdge(i, j); } } @@ -346,9 +320,8 @@ public class NetworkRoutingSat { return toComplete.Last(); } - private void createDemands(int numClients, int numBackbones, int numDemands, - int trafficMin, int trafficMax, - NetworkRoutingData data) { + private void createDemands(int numClients, int numBackbones, int numDemands, int trafficMin, + int trafficMax, NetworkRoutingData data) { while (data.NumberOfDemands < numDemands) { int source = randomClient(numClients, numBackbones); int dest = source; @@ -361,12 +334,10 @@ public class NetworkRoutingSat { } } - private void fillData(int numClients, int numBackbones, int numDemands, - int trafficMin, int trafficMax, int minClientDegree, - int maxClientDegree, int minBackboneDegree, - int maxBackboneDegree, int maxCapacity, - int fixedChargeCost, int seed, - NetworkRoutingData data) { + private void fillData(int numClients, int numBackbones, int numDemands, int trafficMin, + int trafficMax, int minClientDegree, int maxClientDegree, + int minBackboneDegree, int maxBackboneDegree, int maxCapacity, + int fixedChargeCost, int seed, NetworkRoutingData data) { int size = numBackbones + numClients; string name = $"mp_c{numClients}_b{numBackbones}_d{numDemands}.t{trafficMin}-{trafficMax}.cd{minClientDegree}-{maxClientDegree}.bd{minBackboneDegree}-{maxBackboneDegree}.mc{maxCapacity}.fc{fixedChargeCost}.s{seed}"; @@ -376,8 +347,7 @@ public class NetworkRoutingSat { int numArcs = 0; for (int i = 0; i < size - 1; i++) { for (int j = i + 1; j < size; j++) { - if (_network [i] - [j]) { + if (_network[i][j]) { data.AddArc(i, j, maxCapacity); numArcs++; } @@ -391,10 +361,8 @@ public class NetworkRoutingSat { private void addEdge(int i, int j) { _degrees[i]++; _degrees[j]++; - _network [i] - [j] = true; - _network [j] - [i] = true; + _network[i][j] = true; + _network[j][i] = true; } private int randomInInterval(int intervalMin, int intervalMax) { @@ -414,8 +382,7 @@ public class NetworkRoutingSat { } } - [DebuggerDisplay( - "Source {Source} Destination {Destination} Traffic {Traffic}")] + [DebuggerDisplay("Source {Source} Destination {Destination} Traffic {Traffic}")] public struct Demand { public Demand(int source, int destination, int traffic) { Source = source; @@ -437,18 +404,13 @@ public class NetworkRoutingSat { private List> _capacity; private List>> _allPaths; - public int NumberOfNodes { - get; - private set; - } - = -1; + public int NumberOfNodes { get; private set; } = -1; private int countArcs { get { return _arcsData.Count / 2; } } - public void ComputeAllPathsForOneDemandAndOnePathLength(int demandIndex, - int maxLength, + public void ComputeAllPathsForOneDemandAndOnePathLength(int demandIndex, int maxLength, int maxPaths) { // We search for paths of length exactly 'maxLength'. CpModel cpModel = new CpModel(); @@ -481,13 +443,13 @@ public class NetworkRoutingSat { var solver = new CpSolver(); - var solutionPrinter = new FeasibleSolutionChecker( - demandIndex, ref _allPaths, maxLength, arcVars, maxPaths, nodeVars); + var solutionPrinter = new FeasibleSolutionChecker(demandIndex, ref _allPaths, maxLength, + arcVars, maxPaths, nodeVars); var status = solver.SearchAllSolutions(cpModel, solutionPrinter); } - private long[, ] getArcsData() { - long[, ] arcs = new long[_arcsData.Count, 3]; + private long[,] getArcsData() { + long[,] arcs = new long[_arcsData.Count, 3]; for (int i = 0; i < _arcsData.Count; i++) { var data = _arcsData[i]; @@ -504,12 +466,12 @@ public class NetworkRoutingSat { for (int demandIndex = 0; demandIndex < _demands.Count; demandIndex++) { int minPathLength = _allMinPathLengths[demandIndex]; - for (int maxLength = minPathLength + 1; - maxLength <= minPathLength + extraHops + 1; maxLength++) { - ComputeAllPathsForOneDemandAndOnePathLength(demandIndex, maxLength, - maxPaths); + for (int maxLength = minPathLength + 1; maxLength <= minPathLength + extraHops + 1; + maxLength++) { + ComputeAllPathsForOneDemandAndOnePathLength(demandIndex, maxLength, maxPaths); - if (_allPaths[demandIndex].Count >= maxPaths) break; + if (_allPaths[demandIndex].Count >= maxPaths) + break; } numPaths += _allPaths[demandIndex].Count; @@ -529,8 +491,7 @@ public class NetworkRoutingSat { for (int nodeIndex = 0; nodeIndex < NumberOfNodes; nodeIndex++) { _capacity.Add(new List(NumberOfNodes)); for (int i = 0; i < NumberOfNodes; i++) { - _capacity [nodeIndex] - .Add(0); + _capacity[nodeIndex].Add(0); } } @@ -543,10 +504,8 @@ public class NetworkRoutingSat { AddArcData(j, i, arcId); arcId++; _arcCapacity.Add(capacity); - _capacity [i] - [j] = capacity; - _capacity [j] - [i] = capacity; + _capacity[i][j] = capacity; + _capacity[j][i] = capacity; if (printModel) { Console.WriteLine($"Arc {i} <-> {j} with capacity {capacity}"); @@ -585,10 +544,9 @@ public class NetworkRoutingSat { for (int demandIndex = 0; demandIndex < numDemands; demandIndex++) { paths.Clear(); var demand = _demands[demandIndex]; - var r = DijkstraShortestPath(NumberOfNodes, demand.Source, - demand.Destination, - ((int x, int y) p) => hasArc(p.x, p.y), - kDisconnectedDistance, paths); + var r = DijkstraShortestPath(NumberOfNodes, demand.Source, demand.Destination, + ((int x, int y)p) => hasArc(p.x, p.y), kDisconnectedDistance, + paths); _allMinPathLengths.Add(paths.Count - 1); var minPathLength = _allMinPathLengths[demandIndex]; @@ -633,14 +591,12 @@ public class NetworkRoutingSat { Console.WriteLine($" - {numArcs} arcs"); Console.WriteLine($" - {numDemands} demands"); Console.WriteLine($" - a total traffic of {totalDemand}"); - Console.WriteLine( - $" - a minimum cumulated traffic of {totalAccumulatedTraffic}"); + Console.WriteLine($" - a minimum cumulated traffic of {totalAccumulatedTraffic}"); Console.WriteLine($" - {numPaths} possible paths for all demands"); } private long hasArc(int i, int j) { - if (_capacity [i] - [j] > 0) + if (_capacity[i][j] > 0) return 1; else return kDisconnectedDistance; @@ -659,11 +615,10 @@ public class NetworkRoutingSat { pathVars.Add(new List()); for (int arc = 0; arc < numArcs; arc++) { - pathVars [demandIndex] - .Add(cpModel.NewBoolVar("")); + pathVars[demandIndex].Add(cpModel.NewBoolVar("")); } - long[, ] tuples = new long[_allPaths[demandIndex].Count, numArcs]; + long[,] tuples = new long[_allPaths[demandIndex].Count, numArcs]; int pathCount = 0; foreach (var set in _allPaths[demandIndex]) { @@ -674,8 +629,7 @@ public class NetworkRoutingSat { pathCount++; } - var pathCt = - cpModel.AddAllowedAssignments(pathVars[demandIndex], tuples); + var pathCt = cpModel.AddAllowedAssignments(pathVars[demandIndex], tuples); } var trafficVars = new List(numArcs); @@ -692,28 +646,25 @@ public class NetworkRoutingSat { for (int i = 0; i < pathVars.Count; i++) { sumOfTraffic += _demands[i].Traffic; - vars.Add(pathVars [i] - [arcIndex]); + vars.Add(pathVars[i][arcIndex]); traffics.Add(_demands[i].Traffic); } var sum = LinearExpr.ScalProd(vars, traffics); - var trafficVar = - cpModel.NewIntVar(0, sumOfTraffic, $"trafficVar{arcIndex}"); + var trafficVar = cpModel.NewIntVar(0, sumOfTraffic, $"trafficVar{arcIndex}"); trafficVars.Add(trafficVar); cpModel.Add(sum == trafficVar); var capacity = _arcCapacity[arcIndex]; - var scaledTraffic = cpModel.NewIntVar(0, sumOfTraffic * 1000, - $"scaledTrafficVar{arcIndex}"); + var scaledTraffic = + cpModel.NewIntVar(0, sumOfTraffic * 1000, $"scaledTrafficVar{arcIndex}"); var scaledTrafficVar = trafficVar * 1000; cpModel.Add(scaledTrafficVar == scaledTraffic); - var normalizedTraffic = cpModel.NewIntVar( - 0, sumOfTraffic * 1000 / capacity, $"normalizedTraffic{arcIndex}"); + var normalizedTraffic = + cpModel.NewIntVar(0, sumOfTraffic * 1000 / capacity, $"normalizedTraffic{arcIndex}"); - maxNormalizedTraffic = - Math.Max(maxNormalizedTraffic, sumOfTraffic * 1000 / capacity); + maxNormalizedTraffic = Math.Max(maxNormalizedTraffic, sumOfTraffic * 1000 / capacity); cpModel.AddDivisionEquality(normalizedTraffic, scaledTraffic, cpModel.NewConstant(capacity)); normalizedTrafficVars.Add(normalizedTraffic); @@ -724,11 +675,10 @@ public class NetworkRoutingSat { comfortableTrafficVars.Add(comfort); } - var maxUsageCost = - cpModel.NewIntVar(0, maxNormalizedTraffic, "maxUsageCost"); + var maxUsageCost = cpModel.NewIntVar(0, maxNormalizedTraffic, "maxUsageCost"); cpModel.AddMaxEquality(maxUsageCost, normalizedTrafficVars); - var obj = new List(){maxUsageCost}; + var obj = new List() { maxUsageCost }; obj.AddRange(comfortableTrafficVars); cpModel.Minimize(LinearExpr.Sum(obj)); @@ -736,10 +686,9 @@ public class NetworkRoutingSat { solver.StringParameters = parameters; CpSolverStatus status = solver.SearchAllSolutions( - cpModel, new FeasibleSolutionChecker2( - maxUsageCost, comfortableTrafficVars, trafficVars)); + cpModel, new FeasibleSolutionChecker2(maxUsageCost, comfortableTrafficVars, trafficVars)); - return (long) solver.ObjectiveValue; + return (long)solver.ObjectiveValue; } } @@ -753,8 +702,8 @@ public class NetworkRoutingSat { private readonly List _notVisited = new List(); private readonly List _addedToFrontier = new List(); - public DijkstraSP(int nodeCount, int startNode, - Func<(int, int), long> graph, long disconnectedDistance) { + public DijkstraSP(int nodeCount, int startNode, Func<(int, int), long> graph, + long disconnectedDistance) { NodeCount = nodeCount; StartNode = startNode; this._graph = graph; @@ -793,7 +742,7 @@ public class NetworkRoutingSat { private void initialize() { for (int i = 0; i < NodeCount; i++) { - _elements.Add(new Element{Node = i}); + _elements.Add(new Element { Node = i }); if (i == StartNode) { _predecessor[i] = -1; @@ -847,48 +796,32 @@ public class NetworkRoutingSat { } } - public static bool DijkstraShortestPath(int nodeCount, int startNode, - int endNode, - Func<(int, int), long> graph, - long disconnectedDistance, + public static bool DijkstraShortestPath(int nodeCount, int startNode, int endNode, + Func<(int, int), long> graph, long disconnectedDistance, List nodes) { - DijkstraSP bf = - new DijkstraSP(nodeCount, startNode, graph, disconnectedDistance); + DijkstraSP bf = new DijkstraSP(nodeCount, startNode, graph, disconnectedDistance); return bf.ShortestPath(endNode, nodes); } - [DebuggerDisplay( - "Node = {Node}, HeapIndex = {HeapIndex}, Distance = {Distance}")] - private class Element : IHasHeapIndex, - IComparable { - public int HeapIndex { - get; - set; - } - = -1; - public long Distance { - get; - set; - } - = 0; - public int Node { - get; - set; - } - = -1; + [DebuggerDisplay("Node = {Node}, HeapIndex = {HeapIndex}, Distance = {Distance}")] + private class Element : IHasHeapIndex, IComparable { + public int HeapIndex { get; set; } = -1; + public long Distance { get; set; } = 0; + public int Node { get; set; } = -1; public int CompareTo(Element other) { - if (this.Distance > other.Distance) return -1; + if (this.Distance > other.Distance) + return -1; - if (this.Distance < other.Distance) return 1; + if (this.Distance < other.Distance) + return 1; return 0; } } - private class AdjustablePriorityQueue where T : class, - IHasHeapIndex, - IComparable { + private class AdjustablePriorityQueue + where T : class, IHasHeapIndex, IComparable { private readonly List _elems = new List(); public void Add(T val) { @@ -911,51 +844,55 @@ public class NetworkRoutingSat { public bool Contains(T val) { var i = val.HeapIndex; - if (i < 0 || i >= _elems.Count || - _elems [i] - .CompareTo(val) != 0) + if (i < 0 || i >= _elems.Count || _elems[i].CompareTo(val) != 0) return false; return true; } - public T Top() { return _elems[0]; } + public T Top() { + return _elems[0]; + } - public void Pop() { Remove(Top()); } + public void Pop() { + Remove(Top()); + } - public int Size() { return _elems.Count; } + public int Size() { + return _elems.Count; + } public bool IsEmpty { get { return !_elems.Any(); } } - public void Clear() { _elems.Clear(); } + public void Clear() { + _elems.Clear(); + } public void CheckValid() { for (int i = 0; i < _elems.Count; i++) { var leftChild = 1 + 2 * i; if (leftChild < _elems.Count) { - var compare = _elems [i] - .CompareTo(_elems[leftChild]); + var compare = _elems[i].CompareTo(_elems[leftChild]); Debug.Assert(compare >= 0); } int rightChild = leftChild + 1; if (rightChild < _elems.Count) { - var compare = _elems [i] - .CompareTo(_elems[rightChild]); + var compare = _elems[i].CompareTo(_elems[rightChild]); Debug.Assert(compare >= 0); } } } public void NoteChangedPriority(T val) { - if (_elems.Count == 0) return; + if (_elems.Count == 0) + return; var i = val.HeapIndex; var parent = (i - 1) / 2; - if (_elems [parent] - .CompareTo(val) == -1) { + if (_elems[parent].CompareTo(val) == -1) { adjustUpwards(i); } else { adjustDownwards(i); @@ -966,8 +903,7 @@ public class NetworkRoutingSat { var t = _elems[i]; while (i > 0) { var parent = (i - 1) / 2; - if (_elems [parent] - .CompareTo(t) != -1) { + if (_elems[parent].CompareTo(t) != -1) { break; } @@ -989,11 +925,10 @@ public class NetworkRoutingSat { } var rightChild = leftChild + 1; - var next = (rightChild < _elems.Count && - _elems [leftChild] - .CompareTo(_elems[rightChild]) == -1) - ? rightChild - : leftChild; + var next = + (rightChild < _elems.Count && _elems[leftChild].CompareTo(_elems[rightChild]) == -1) + ? rightChild + : leftChild; if (t.CompareTo(_elems[next]) != -1) { break; @@ -1010,17 +945,13 @@ public class NetworkRoutingSat { } public interface IHasHeapIndex { - int HeapIndex { - get; - set; - } + int HeapIndex { get; set; } } private class FeasibleSolutionChecker : CpSolverSolutionCallback { - public FeasibleSolutionChecker(int demandIndex, - ref List>> allPaths, - int maxLength, List arcVars, - int maxPaths, List nodeVars) { + public FeasibleSolutionChecker(int demandIndex, ref List>> allPaths, + int maxLength, List arcVars, int maxPaths, + List nodeVars) { DemandIndex = demandIndex; AllPaths = allPaths; MaxLength = maxLength; @@ -1041,19 +972,14 @@ public class NetworkRoutingSat { AllPaths.Add(new List>()); int pathId = AllPaths[DemandIndex].Count; - AllPaths [DemandIndex] - .Add(new HashSet()); + AllPaths[DemandIndex].Add(new HashSet()); for (int i = 0; i < MaxLength - 1; i++) { - int arc = (int) this.SolutionIntegerValue(ArcVars [i] - .GetIndex()); - AllPaths [DemandIndex] - [pathId] - .Add(arc); + int arc = (int)this.SolutionIntegerValue(ArcVars[i].GetIndex()); + AllPaths[DemandIndex][pathId].Add(arc); } - if (AllPaths [DemandIndex] - .Count() >= MaxPaths) { + if (AllPaths[DemandIndex].Count() >= MaxPaths) { StopSearch(); } } @@ -1065,8 +991,7 @@ public class NetworkRoutingSat { public List TrafficVars { get; } private int _numSolutions = 0; - public FeasibleSolutionChecker2(IntVar maxUsageCost, - List comfortableTrafficVars, + public FeasibleSolutionChecker2(IntVar maxUsageCost, List comfortableTrafficVars, List trafficVars) { MaxUsageCost = maxUsageCost; ComfortableTrafficVars = comfortableTrafficVars; @@ -1079,16 +1004,14 @@ public class NetworkRoutingSat { int numNonComfortableArcs = 0; foreach (var comfort in ComfortableTrafficVars) { - numNonComfortableArcs += - SolutionBooleanValue(comfort.GetIndex()) ? 1 : 0; + numNonComfortableArcs += SolutionBooleanValue(comfort.GetIndex()) ? 1 : 0; } if (numNonComfortableArcs > 0) { Console.WriteLine( $"*** Found a solution with a max usage of {percent}%, and {numNonComfortableArcs} links above the comfort zone"); } else { - Console.WriteLine( - $"*** Found a solution with a max usage of {percent}%"); + Console.WriteLine($"*** Found a solution with a max usage of {percent}%"); } _numSolutions++; diff --git a/examples/dotnet/NursesSat.cs b/examples/dotnet/NursesSat.cs index 4b45c34c98..81b7f9a18a 100644 --- a/examples/dotnet/NursesSat.cs +++ b/examples/dotnet/NursesSat.cs @@ -17,8 +17,7 @@ using System.Linq; using Google.OrTools.Sat; public class NurseSolutionObserver : CpSolverSolutionCallback { - public NurseSolutionObserver(IntVar[, , ] shifts, int num_nurses, - int num_days, int num_shifts, + public NurseSolutionObserver(IntVar[,,] shifts, int num_nurses, int num_days, int num_shifts, HashSet to_print) { shifts_ = shifts; num_nurses_ = num_nurses; @@ -30,15 +29,14 @@ public class NurseSolutionObserver : CpSolverSolutionCallback { public override void OnSolutionCallback() { solution_count_++; if (to_print_.Contains(solution_count_)) { - Console.WriteLine(String.Format("Solution #{0}: time = {1:.02} s", - solution_count_, WallTime())); + Console.WriteLine( + String.Format("Solution #{0}: time = {1:.02} s", solution_count_, WallTime())); for (int d = 0; d < num_days_; ++d) { Console.WriteLine(String.Format("Day #{0}", d)); for (int n = 0; n < num_nurses_; ++n) { for (int s = 0; s < num_shifts_; ++s) { if (BooleanValue(shifts_[n, d, s])) { - Console.WriteLine( - String.Format(" Nurse #{0} is working shift #{1}", n, s)); + Console.WriteLine(String.Format(" Nurse #{0} is working shift #{1}", n, s)); } } } @@ -46,10 +44,12 @@ public class NurseSolutionObserver : CpSolverSolutionCallback { } } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; - private IntVar[, , ] shifts_; + private IntVar[,,] shifts_; private int num_nurses_; private int num_days_; private int num_shifts_; @@ -74,12 +74,11 @@ public class NursesSat { // Creates shift variables. // shift[n, d, s]: nurse "n" works shift "s" on day "d". - IntVar[, , ] shift = new IntVar[num_nurses, num_days, num_shifts]; + IntVar[,,] shift = new IntVar[num_nurses, num_days, num_shifts]; foreach (int n in all_nurses) { foreach (int d in all_days) { foreach (int s in all_shifts) { - shift[n, d, s] = - model.NewBoolVar(String.Format("shift_n{0}d{1}s{2}", n, d, s)); + shift[n, d, s] = model.NewBoolVar(String.Format("shift_n{0}d{1}s{2}", n, d, s)); } } } @@ -121,11 +120,10 @@ public class NursesSat { // works_shift[(n, s)] is 1 if nurse n works shift s at least one day in // the week. - IntVar[, ] works_shift = new IntVar[num_nurses, num_shifts]; + IntVar[,] works_shift = new IntVar[num_nurses, num_shifts]; foreach (int n in all_nurses) { foreach (int s in all_shifts) { - works_shift[n, s] = - model.NewBoolVar(String.Format("works_shift_n{0}s{1}", n, s)); + works_shift[n, s] = model.NewBoolVar(String.Format("works_shift_n{0}s{1}", n, s)); IntVar[] tmp = new IntVar[num_days]; foreach (int d in all_days) { tmp[d] = shift[n, d, s]; @@ -154,10 +152,8 @@ public class NursesSat { foreach (int d in all_days) { int yesterday = d == 0 ? num_days - 1 : d - 1; int tomorrow = d == num_days - 1 ? 0 : d + 1; - model.AddBoolOr(new ILiteral[]{shift[n, yesterday, s], - shift [n, d, s] - .Not(), - shift[n, tomorrow, s]}); + model.AddBoolOr(new ILiteral[] { shift[n, yesterday, s], shift[n, d, s].Not(), + shift[n, tomorrow, s] }); } } } @@ -170,8 +166,8 @@ public class NursesSat { to_print.Add(2034); to_print.Add(5091); to_print.Add(7003); - NurseSolutionObserver cb = new NurseSolutionObserver( - shift, num_nurses, num_days, num_shifts, to_print); + NurseSolutionObserver cb = + new NurseSolutionObserver(shift, num_nurses, num_days, num_shifts, to_print); CpSolverStatus status = solver.SearchAllSolutions(model, cb); // Statistics. diff --git a/examples/dotnet/ShiftSchedulingSat.cs b/examples/dotnet/ShiftSchedulingSat.cs index 73dda58275..6aa76840f4 100644 --- a/examples/dotnet/ShiftSchedulingSat.cs +++ b/examples/dotnet/ShiftSchedulingSat.cs @@ -20,87 +20,86 @@ using Google.OrTools.Sat; /// Creates a shift scheduling problem and solves it /// public class ShiftSchedulingSat { - static void Main(string[] args) { SolveShiftScheduling(); } + static void Main(string[] args) { + SolveShiftScheduling(); + } static void SolveShiftScheduling() { int numEmployees = 8; int numWeeks = 3; - var shifts = new[]{"O", "M", "A", "N"}; + var shifts = new[] { "O", "M", "A", "N" }; // Fixed assignment: (employee, shift, day). // This fixes the first 2 days of the schedule. - var fixedAssignments = new (int Employee, int Shift, int Day)[]{ - (0, 0, 0), (1, 0, 0), (2, 1, 0), (3, 1, 0), (4, 2, 0), (5, 2, 0), - (6, 2, 3), (7, 3, 0), (0, 1, 1), (1, 1, 1), (2, 2, 1), (3, 2, 1), - (4, 2, 1), (5, 0, 1), (6, 0, 1), (7, 3, 1), + var fixedAssignments = new(int Employee, int Shift, int Day)[] { + (0, 0, 0), (1, 0, 0), (2, 1, 0), (3, 1, 0), (4, 2, 0), (5, 2, 0), (6, 2, 3), (7, 3, 0), + (0, 1, 1), (1, 1, 1), (2, 2, 1), (3, 2, 1), (4, 2, 1), (5, 0, 1), (6, 0, 1), (7, 3, 1), }; // Request: (employee, shift, day, weight) // A negative weight indicates that the employee desire this assignment. - var requests = new (int Employee, int Shift, int Day, int Weight)[]{ - // Employee 3 wants the first Saturday off. - (3, 0, 5, -2), - // Employee 5 wants a night shift on the second Thursday. - (5, 3, 10, -2), - // Employee 2 does not want a night shift on the third Friday. - (2, 3, 4, 4)}; + var requests = new(int Employee, int Shift, int Day, int Weight)[] { + // Employee 3 wants the first Saturday off. + (3, 0, 5, -2), + // Employee 5 wants a night shift on the second Thursday. + (5, 3, 10, -2), + // Employee 2 does not want a night shift on the third Friday. + (2, 3, 4, 4) + }; // Shift constraints on continuous sequence : // (shift, hard_min, soft_min, min_penalty, // soft_max, hard_max, max_penalty) - var shiftConstraints = - new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, - int HardMax, int MaxPenalty)[]{ - // One or two consecutive days of rest, this is a hard constraint. - (0, 1, 1, 0, 2, 2, 0), - // Between 2 and 3 consecutive days of night shifts, 1 and 4 are - // possible but penalized. - (3, 1, 2, 20, 3, 4, 5), - }; + var shiftConstraints = new(int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, + int HardMax, int MaxPenalty)[] { + // One or two consecutive days of rest, this is a hard constraint. + (0, 1, 1, 0, 2, 2, 0), + // Between 2 and 3 consecutive days of night shifts, 1 and 4 are + // possible but penalized. + (3, 1, 2, 20, 3, 4, 5), + }; // Weekly sum constraints on shifts days: // (shift, hardMin, softMin, minPenalty, // softMax, hardMax, maxPenalty) - var weeklySumConstraints = - new (int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, - int HardMax, int MaxPenalty)[]{ - // Constraints on rests per week. - (0, 1, 2, 7, 2, 3, 4), - // At least 1 night shift per week (penalized). At most 4 (hard). - (3, 0, 1, 3, 4, 4, 0), - }; + var weeklySumConstraints = new(int Shift, int HardMin, int SoftMin, int MinPenalty, int SoftMax, + int HardMax, int MaxPenalty)[] { + // Constraints on rests per week. + (0, 1, 2, 7, 2, 3, 4), + // At least 1 night shift per week (penalized). At most 4 (hard). + (3, 0, 1, 3, 4, 4, 0), + }; // Penalized transitions: // (previous_shift, next_shift, penalty (0 means forbidden)) - var penalizedTransitions = - new (int PreviousShift, int NextShift, int Penalty)[]{ - // Afternoon to night has a penalty of 4. - (2, 3, 4), - // Night to morning is forbidden. - (3, 1, 0), - }; + var penalizedTransitions = new(int PreviousShift, int NextShift, int Penalty)[] { + // Afternoon to night has a penalty of 4. + (2, 3, 4), + // Night to morning is forbidden. + (3, 1, 0), + }; // daily demands for work shifts (morning, afternon, night) for each day // of the week starting on Monday. - var weeklyCoverDemands = new int[][]{ - new[]{2, 3, 1}, // Monday - new[]{2, 3, 1}, // Tuesday - new[]{2, 2, 2}, // Wednesday - new[]{2, 3, 1}, // Thursday - new[]{2, 2, 2}, // Friday - new[]{1, 2, 3}, // Saturday - new[]{1, 3, 1}, // Sunday + var weeklyCoverDemands = new int[][] { + new[] { 2, 3, 1 }, // Monday + new[] { 2, 3, 1 }, // Tuesday + new[] { 2, 2, 2 }, // Wednesday + new[] { 2, 3, 1 }, // Thursday + new[] { 2, 2, 2 }, // Friday + new[] { 1, 2, 3 }, // Saturday + new[] { 1, 3, 1 }, // Sunday }; // Penalty for exceeding the cover constraint per shift type. - var excessCoverPenalties = new[]{2, 2, 5}; + var excessCoverPenalties = new[] { 2, 2, 5 }; var numDays = numWeeks * 7; var numShifts = shifts.Length; var model = new CpModel(); - IntVar[, , ] work = new IntVar[numEmployees, numShifts, numDays]; + IntVar[,,] work = new IntVar[numEmployees, numShifts, numDays]; foreach (int e in Range(numEmployees)) { foreach (int s in Range(numShifts)) { @@ -129,12 +128,12 @@ public class ShiftSchedulingSat { } // Fixed assignments. - foreach (var(e, s, d) in fixedAssignments) { + foreach (var (e, s, d) in fixedAssignments) { model.Add(work[e, s, d] == 1); } // Employee requests - foreach (var(e, s, d, w) in requests) { + foreach (var (e, s, d, w) in requests) { objBoolVars.Add(work[e, s, d]); objBoolCoeffs.Add(w); } @@ -147,10 +146,9 @@ public class ShiftSchedulingSat { works[d] = work[e, constraint.Shift, d]; } - var(variables, coeffs) = AddSoftSequenceConstraint( - model, works, constraint.HardMin, constraint.SoftMin, - constraint.MinPenalty, constraint.SoftMax, constraint.HardMax, - constraint.MaxPenalty, + var (variables, coeffs) = AddSoftSequenceConstraint( + model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, + constraint.SoftMax, constraint.HardMax, constraint.MaxPenalty, $"shift_constraint(employee {e}, shift {constraint.Shift}"); objBoolVars.AddRange(variables); @@ -168,10 +166,9 @@ public class ShiftSchedulingSat { works[d] = work[e, constraint.Shift, d + w * 7]; } - var(variables, coeffs) = AddSoftSumConstraint( - model, works, constraint.HardMin, constraint.SoftMin, - constraint.MinPenalty, constraint.SoftMax, constraint.HardMax, - constraint.MaxPenalty, + var (variables, coeffs) = AddSoftSumConstraint( + model, works, constraint.HardMin, constraint.SoftMin, constraint.MinPenalty, + constraint.SoftMax, constraint.HardMax, constraint.MaxPenalty, $"weekly_sum_constraint(employee {e}, shift {constraint.Shift}, week {w}"); objBoolVars.AddRange(variables); @@ -184,17 +181,14 @@ public class ShiftSchedulingSat { foreach (var penalizedTransition in penalizedTransitions) { foreach (int e in Range(numEmployees)) { foreach (int d in Range(numDays - 1)) { - var transition = new List(){ - work [e, penalizedTransition.PreviousShift, d] - .Not(), - work [e, penalizedTransition.NextShift, d + 1] - .Not()}; + var transition = + new List() { work[e, penalizedTransition.PreviousShift, d].Not(), + work[e, penalizedTransition.NextShift, d + 1].Not() }; if (penalizedTransition.Penalty == 0) { model.AddBoolOr(transition); } else { - var transVar = - model.NewBoolVar($"transition (employee {e}, day={d}"); + var transVar = model.NewBoolVar($"transition (employee {e}, day={d}"); transition.Add(transVar); model.AddBoolOr(transition); objBoolVars.Add(transVar); @@ -214,8 +208,7 @@ public class ShiftSchedulingSat { } // Ignore off shift - var minDemand = weeklyCoverDemands [d] - [s - 1]; + var minDemand = weeklyCoverDemands[d][s - 1]; var worked = model.NewIntVar(minDemand, numEmployees, ""); model.Add(LinearExpr.Sum(works) == worked); @@ -270,7 +263,7 @@ public class ShiftSchedulingSat { Console.WriteLine(); Console.WriteLine("Penalties:"); - foreach (var(i, var) in objBoolVars.Select((x, i) =>(i, x))) { + foreach (var (i, var) in objBoolVars.Select((x, i) => (i, x))) { if (solver.BooleanValue(var)) { var penalty = objBoolCoeffs[i]; if (penalty > 0) { @@ -281,7 +274,7 @@ public class ShiftSchedulingSat { } } - foreach (var(i, var) in objIntVars.Select((x, i) =>(i, x))) { + foreach (var (i, var) in objIntVars.Select((x, i) => (i, x))) { if (solver.Value(var) > 0) { Console.WriteLine( $" {var.Name()} violated by {solver.Value(var)}, linear penalty={objIntCoeffs[i]}"); @@ -312,13 +305,13 @@ public class ShiftSchedulingSat { static ILiteral[] NegatedBoundedSpan(IntVar[] works, int start, int length) { var sequence = new List(); - if (start > 0) sequence.Add(works[start - 1]); + if (start > 0) + sequence.Add(works[start - 1]); - foreach (var i in Range(length)) - sequence.Add(works [start + i] - .Not()); + foreach (var i in Range(length)) sequence.Add(works[start + i].Not()); - if (start + length < works.Length) sequence.Add(works[start + length]); + if (start + length < works.Length) + sequence.Add(works[start + length]); return sequence.ToArray(); } @@ -345,10 +338,9 @@ public class ShiftSchedulingSat { /// base name for penalty literals. A tuple (costLiterals, /// costCoefficients) containing the different penalties created by the /// sequence constraint. - static(IntVar[] costLiterals, int[] costCoefficients) - AddSoftSequenceConstraint(CpModel model, IntVar[] works, int hardMin, - int softMin, int minCost, int softMax, - int hardMax, int maxCost, string prefix) { + static (IntVar[] costLiterals, int[] costCoefficients) + AddSoftSequenceConstraint(CpModel model, IntVar[] works, int hardMin, int softMin, + int minCost, int softMax, int hardMax, int maxCost, string prefix) { var costLiterals = new List(); var costCoefficients = new List(); @@ -398,8 +390,7 @@ public class ShiftSchedulingSat { var temp = new List(); foreach (var i in Range(start, start + hardMax + 1)) { - temp.Add(works [i] - .Not()); + temp.Add(works[i].Not()); } model.AddBoolOr(temp); @@ -429,10 +420,9 @@ public class ShiftSchedulingSat { /// base name for penalty literals. A tuple (costVariables, /// costCoefficients) containing the different penalties created by the /// sequence constraint. - static(IntVar[] costVariables, int[] costCoefficients) - AddSoftSumConstraint(CpModel model, IntVar[] works, int hardMin, - int softMin, int minCost, int softMax, int hardMax, - int maxCost, string prefix) { + static (IntVar[] costVariables, int[] costCoefficients) + AddSoftSumConstraint(CpModel model, IntVar[] works, int hardMin, int softMin, int minCost, + int softMax, int hardMax, int maxCost, string prefix) { var costVariables = new List(); var costCoefficients = new List(); var sumVar = model.NewIntVar(hardMin, hardMax, ""); @@ -447,7 +437,7 @@ public class ShiftSchedulingSat { var delta = model.NewIntVar(-works.Length, works.Length, ""); model.Add(delta == (softMin - sumVar)); var excess = model.NewIntVar(0, works.Length, prefix + ": under_sum"); - model.AddMaxEquality(excess, new[]{delta, zero}); + model.AddMaxEquality(excess, new[] { delta, zero }); costVariables.Add(excess); costCoefficients.Add(minCost); } @@ -457,7 +447,7 @@ public class ShiftSchedulingSat { var delta = model.NewIntVar(-works.Length, works.Length, ""); model.Add(delta == sumVar - softMax); var excess = model.NewIntVar(0, works.Length, prefix + ": over_sum"); - model.AddMaxEquality(excess, new[]{delta, zero}); + model.AddMaxEquality(excess, new[] { delta, zero }); costVariables.Add(excess); costCoefficients.Add(maxCost); } @@ -480,5 +470,7 @@ public class ShiftSchedulingSat { /// /// The exclusive stop. /// A sequence of integers. - static IEnumerable Range(int stop) { return Range(0, stop); } + static IEnumerable Range(int stop) { + return Range(0, stop); + } } diff --git a/examples/dotnet/SpeakerSchedulingSat.cs b/examples/dotnet/SpeakerSchedulingSat.cs index 9df618fb25..a16c9e00f4 100644 --- a/examples/dotnet/SpeakerSchedulingSat.cs +++ b/examples/dotnet/SpeakerSchedulingSat.cs @@ -33,82 +33,68 @@ class SpeakerScheduling { // the slots each speaker is available int[][] speaker_availability = { - new int[]{1, 3, 4, 6, 7, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, + new int[] { 1, 3, 4, 6, 7, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, - 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59}, - new int[]{1, 2, 7, 8, 10, 11, 16, 17, 18, 21, 22, 23, 24, - 25, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, - 46, 47, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 60}, - new int[]{5, 6, 7, 10, 12, 14, 16, 17, 21, 22, 23, - 24, 33, 35, 37, 38, 39, 40, 41, 42, 43, 44, - 45, 46, 51, 53, 55, 56, 57, 58, 59}, - new int[]{1, 2, 3, 4, 5, 6, 7, 11, 13, 14, 15, 16, 20, 24, - 25, 33, 34, 35, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60}, - new int[]{4, 7, 8, 9, 16, 17, 19, 20, 21, 22, 23, 24, - 25, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, - 49, 50, 51, 53, 55, 56, 57, 58, 59, 60}, - new int[]{4, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, - 22, 23, 24, 33, 34, 35, 36, 38, 39, 42, 44, - 46, 48, 49, 51, 53, 54, 55, 56, 57}, - new int[]{1, 2, 3, 4, 5, 6, 7, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 54, 55, 56, 57, 58, 59, 60}, - new int[]{1, 3, 11, 14, 15, 16, 17, 21, 22, 23, 24, 25, - 33, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 47, - 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60}, - new int[]{1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 18, 19, 20, 21, + 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 59 }, + new int[] { 1, 2, 7, 8, 10, 11, 16, 17, 18, 21, 22, 23, 24, 25, 33, 34, 35, 36, 37, 38, + 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, + new int[] { 5, 6, 7, 10, 12, 14, 16, 17, 21, 22, 23, 24, 33, 35, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 51, 53, 55, 56, 57, 58, 59 }, + new int[] { 1, 2, 3, 4, 5, 6, 7, 11, 13, 14, 15, 16, 20, 24, 25, 33, 34, 35, 37, 38, + 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60 }, + new int[] { 4, 7, 8, 9, 16, 17, 19, 20, 21, 22, 23, 24, 25, 33, 34, 35, 36, + 37, 38, 39, 40, 41, 42, 43, 49, 50, 51, 53, 55, 56, 57, 58, 59, 60 }, + new int[] { 4, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 22, 23, 24, 33, 34, + 35, 36, 38, 39, 42, 44, 46, 48, 49, 51, 53, 54, 55, 56, 57 }, + new int[] { 1, 2, 3, 4, 5, 6, 7, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 54, 55, 56, 57, 58, 59, 60 }, + new int[] { 1, 3, 11, 14, 15, 16, 17, 21, 22, 23, 24, 25, 33, 35, 36, 37, 39, 40, + 41, 42, 43, 44, 45, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, + new int[] { 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 18, 19, 20, 21, 22, 23, 24, 25, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, - 44, 45, 46, 50, 51, 52, 53, 54, 55, 56, 57, 59, 60}, - new int[]{24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60}, - new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 16, 17, 18, 19, 20, 22, 23, 24, 25, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 50, 51, 52, 53, 55, 56, 57, 58, 59, 60}, - new int[]{3, 4, 5, 6, 13, 15, 16, 17, 18, 19, 21, 22, - 24, 25, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, - 44, 45, 47, 52, 53, 55, 57, 58, 59, 60}, - new int[]{4, 5, 6, 8, 11, 12, 13, 14, 17, 19, 20, 22, - 23, 24, 25, 33, 34, 35, 36, 37, 39, 40, 41, 42, - 43, 47, 48, 49, 50, 51, 52, 55, 56, 57}, - new int[]{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60}, - new int[]{12, 25, 33, 35, 36, 37, 39, 41, 42, 43, 48, 51, 52, 53, 54, - 57, 59, 60}, - new int[]{4, 8, 16, 17, 19, 23, 25, 33, 34, 35, 37, 41, 44, 45, 47, 48, - 49, 50}, - new int[]{3, 23, 24, 25, 33, 35, 36, 37, 38, 39, 40, 42, - 43, 44, 49, 50, 53, 54, 55, 56, 57, 58, 60}, - new int[]{7, 13, 19, 20, 22, 23, 24, 25, 33, 34, 35, 38, 40, 41, - 42, 44, 45, 46, 47, 48, 49, 52, 53, 54, 58, 59, 60}}; + 44, 45, 46, 50, 51, 52, 53, 54, 55, 56, 57, 59, 60 }, + new int[] { 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, + new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, + 19, 20, 22, 23, 24, 25, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60 }, + new int[] { 3, 4, 5, 6, 13, 15, 16, 17, 18, 19, 21, 22, 24, 25, 33, 34, 35, + 36, 37, 39, 40, 41, 42, 43, 44, 45, 47, 52, 53, 55, 57, 58, 59, 60 }, + new int[] { 4, 5, 6, 8, 11, 12, 13, 14, 17, 19, 20, 22, 23, 24, 25, 33, 34, + 35, 36, 37, 39, 40, 41, 42, 43, 47, 48, 49, 50, 51, 52, 55, 56, 57 }, + new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 25, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 }, + new int[] { 12, 25, 33, 35, 36, 37, 39, 41, 42, 43, 48, 51, 52, 53, 54, 57, 59, 60 }, + new int[] { 4, 8, 16, 17, 19, 23, 25, 33, 34, 35, 37, 41, 44, 45, 47, 48, 49, 50 }, + new int[] { 3, 23, 24, 25, 33, 35, 36, 37, 38, 39, 40, 42, + 43, 44, 49, 50, 53, 54, 55, 56, 57, 58, 60 }, + new int[] { 7, 13, 19, 20, 22, 23, 24, 25, 33, 34, 35, 38, 40, 41, + 42, 44, 45, 46, 47, 48, 49, 52, 53, 54, 58, 59, 60 } + }; // how long each talk lasts for each speaker - int[] durations = {1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + int[] durations = { 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; int sum_of_durations = durations.Sum(); int number_of_speakers = durations.Length; // calculate the total number of slots (maximum in the availability array) // (and add the max durations) int last_slot = - (from s in Enumerable - .Range(0, number_of_speakers) select speaker_availability [s] - .Max()) + (from s in Enumerable.Range(0, number_of_speakers) select speaker_availability[s].Max()) .Max(); - Console.WriteLine( - $"Scheduling {number_of_speakers} speakers, for a total of " + - $"{sum_of_durations} slots, during [{first_slot}..{last_slot}]"); + Console.WriteLine($"Scheduling {number_of_speakers} speakers, for a total of " + + $"{sum_of_durations} slots, during [{first_slot}..{last_slot}]"); CpModel model = new CpModel(); // We store the possible entries (var, start) for all talks filtered // from the duration and the speaker availability. - List[] entries = new List[ number_of_speakers ]; + List[] entries = new List[number_of_speakers]; for (int speaker = 0; speaker < number_of_speakers; ++speaker) { entries[speaker] = new List(); } - List[] contributions_per_slot = new List[ last_slot + 1 ]; + List[] contributions_per_slot = new List[last_slot + 1]; for (int slot = 1; slot <= last_slot; ++slot) { contributions_per_slot[slot] = new List(); } @@ -120,29 +106,24 @@ class SpeakerScheduling { int availability = speaker_availability[speaker].Length; for (int index = 0; index < availability; ++index) { bool ok = true; - int slot = speaker_availability [speaker] - [index]; + int slot = speaker_availability[speaker][index]; if (slot < first_slot) { continue; } for (int offset = 1; offset < duration; ++offset) { - if (index + offset >= availability || speaker_availability [speaker] - [index + offset] != - slot + offset) { + if (index + offset >= availability || + speaker_availability[speaker][index + offset] != slot + offset) { // discontinuity. ok = false; break; } } if (ok) { - IntVar var = model.NewBoolVar("speaker " + (speaker + 1) + - " starts at " + slot); - entries [speaker] - .Add(new Entry(var, slot)); + IntVar var = model.NewBoolVar("speaker " + (speaker + 1) + " starts at " + slot); + entries[speaker].Add(new Entry(var, slot)); all_vars.Add(var); for (int offset = 0; offset < duration; ++offset) { - contributions_per_slot [slot + offset] - .Add(var); + contributions_per_slot[slot + offset].Add(var); } } } @@ -154,8 +135,8 @@ class SpeakerScheduling { } // Creates last_slot. - IntVar last_slot_var = model.NewIntVar(first_slot + sum_of_durations - 1, - last_slot, "last_slot"); + IntVar last_slot_var = + model.NewIntVar(first_slot + sum_of_durations - 1, last_slot, "last_slot"); for (int speaker = 0; speaker < number_of_speakers; speaker++) { int duration = durations[speaker]; foreach (Entry e in entries[speaker]) { @@ -176,8 +157,8 @@ class SpeakerScheduling { for (int speaker = 0; speaker < number_of_speakers; speaker++) { foreach (Entry e in entries[speaker]) { if (solver.BooleanValue(e.var)) { - Console.WriteLine(" - speaker {0,2}: {1,2}..{2,2}", (speaker + 1), - e.start, (e.start + durations[speaker] - 1)); + Console.WriteLine(" - speaker {0,2}: {1,2}..{2,2}", (speaker + 1), e.start, + (e.start + durations[speaker] - 1)); } } } diff --git a/examples/dotnet/TaskSchedulingSat.cs b/examples/dotnet/TaskSchedulingSat.cs index 67932bf75a..ac53cab930 100644 --- a/examples/dotnet/TaskSchedulingSat.cs +++ b/examples/dotnet/TaskSchedulingSat.cs @@ -3,15 +3,11 @@ using System.Collections.Generic; using Google.OrTools.Sat; class Job { - public Job(List tasks) { AlternativeTasks = tasks; } - public Job Successor { - get; - set; - } - public List AlternativeTasks { - get; - set; + public Job(List tasks) { + AlternativeTasks = tasks; } + public Job Successor { get; set; } + public List AlternativeTasks { get; set; } } class Task { @@ -21,29 +17,17 @@ class Task { Equipment = equipment; } - public string Name { - get; - set; - } - public long StartTime { - get; - set; - } + public string Name { get; set; } + public long StartTime { get; set; } public long EndTime { get { return StartTime + Duration; } } - public long Duration { - get; - set; - } - public long Equipment { - get; - set; - } + public long Duration { get; set; } + public long Equipment { get; set; } public override string ToString() { - return Name + " [ " + Equipment + " ]\tstarts: " + StartTime + - " ends:" + EndTime + ", duration: " + Duration; + return Name + " [ " + Equipment + " ]\tstarts: " + StartTime + " ends:" + EndTime + + ", duration: " + Duration; } } @@ -51,8 +35,7 @@ class TaskSchedulingSat { public static List myJobList = new List(); public static Dictionary> tasksToEquipment = new Dictionary>(); - public static Dictionary taskIndexes = - new Dictionary(); + public static Dictionary taskIndexes = new Dictionary(); public static void InitTaskList() { List taskList = new List(); @@ -136,7 +119,8 @@ class TaskSchedulingSat { public static int GetEndTaskCount() { int c = 0; foreach (Job j in myJobList) - if (j.Successor == null) c += j.AlternativeTasks.Count; + if (j.Successor == null) + c += j.AlternativeTasks.Count; return c; } @@ -160,13 +144,12 @@ class TaskSchedulingSat { tmp[i++] = taskChoosed[ti]; IntVar start = model.NewIntVar(0, 10000, t.Name + "_start"); IntVar end = model.NewIntVar(0, 10000, t.Name + "_end"); - tasks[ti] = - model.NewIntervalVar(start, t.Duration, end, t.Name + "_interval"); - if (j.Successor == null) allEnds[endJobCounter++] = end; + tasks[ti] = model.NewIntervalVar(start, t.Duration, end, t.Name + "_interval"); + if (j.Successor == null) + allEnds[endJobCounter++] = end; if (!tasksToEquipment.ContainsKey(t.Equipment)) tasksToEquipment[t.Equipment] = new List(); - tasksToEquipment [t.Equipment] - .Add(tasks[ti]); + tasksToEquipment[t.Equipment].Add(tasks[ti]); } model.Add(LinearExpr.Sum(tmp) == 1); } diff --git a/examples/dotnet/cscvrptw.cs b/examples/dotnet/cscvrptw.cs index c07314819a..77622581fa 100644 --- a/examples/dotnet/cscvrptw.cs +++ b/examples/dotnet/cscvrptw.cs @@ -63,23 +63,20 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { /// positions of two different indices. /// class Manhattan { - public Manhattan(RoutingIndexManager manager, Position[] locations, - int coefficient) { + public Manhattan(RoutingIndexManager manager, Position[] locations, int coefficient) { this.manager_ = manager; this.locations_ = locations; this.coefficient_ = coefficient; } public long Call(long first_index, long second_index) { - if (first_index >= locations_.Length || - second_index >= locations_.Length) { + if (first_index >= locations_.Length || second_index >= locations_.Length) { return 0; } int first_node = manager_.IndexToNode(first_index); int second_node = manager_.IndexToNode(second_index); return (Math.Abs(locations_[first_node].x_ - locations_[second_node].x_) + - Math.Abs(locations_[first_node].y_ - - locations_[second_node].y_)) * + Math.Abs(locations_[first_node].y_ - locations_[second_node].y_)) * coefficient_; } @@ -156,9 +153,8 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { /// /// maximum pernalty cost if order is dropped. /// - private void BuildOrders(int number_of_orders, int number_of_vehicles, - int x_max, int y_max, int demand_max, - int time_window_max, int time_window_width, + private void BuildOrders(int number_of_orders, int number_of_vehicles, int x_max, int y_max, + int demand_max, int time_window_max, int time_window_width, int penalty_min, int penalty_max) { Console.WriteLine("Building orders."); locations_ = new Position[number_of_orders + 2 * number_of_vehicles]; @@ -166,14 +162,13 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { order_time_windows_ = new TimeWindow[number_of_orders]; order_penalties_ = new int[number_of_orders]; for (int order = 0; order < number_of_orders; ++order) { - locations_[order] = new Position(random_generator.Next(x_max + 1), - random_generator.Next(y_max + 1)); + locations_[order] = + new Position(random_generator.Next(x_max + 1), random_generator.Next(y_max + 1)); order_demands_[order] = random_generator.Next(demand_max + 1); int time_window_start = random_generator.Next(time_window_max + 1); - order_time_windows_[order] = new TimeWindow( - time_window_start, time_window_start + time_window_width); - order_penalties_[order] = - random_generator.Next(penalty_max - penalty_min + 1) + penalty_min; + order_time_windows_[order] = + new TimeWindow(time_window_start, time_window_start + time_window_width); + order_penalties_[order] = random_generator.Next(penalty_max - penalty_min + 1) + penalty_min; } } @@ -192,9 +187,8 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { /// capacity of a vehicle. /// maximum cost per distance unit of a /// vehicle (minimum is 1) - private void BuildFleet(int number_of_orders, int number_of_vehicles, - int x_max, int y_max, int end_time, int capacity, - int cost_coefficient_max) { + private void BuildFleet(int number_of_orders, int number_of_vehicles, int x_max, int y_max, + int end_time, int capacity, int cost_coefficient_max) { Console.WriteLine("Building fleet."); vehicle_capacity_ = capacity; vehicle_starts_ = new int[number_of_vehicles]; @@ -204,14 +198,13 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { int index = 2 * vehicle + number_of_orders; vehicle_starts_[vehicle] = index; - locations_[index] = new Position(random_generator.Next(x_max + 1), - random_generator.Next(y_max + 1)); + locations_[index] = + new Position(random_generator.Next(x_max + 1), random_generator.Next(y_max + 1)); vehicle_ends_[vehicle] = index + 1; - locations_[index + 1] = new Position(random_generator.Next(x_max + 1), - random_generator.Next(y_max + 1)); + locations_[index + 1] = + new Position(random_generator.Next(x_max + 1), random_generator.Next(y_max + 1)); vehicle_end_time_[vehicle] = end_time; - vehicle_cost_coefficients_[vehicle] = - random_generator.Next(cost_coefficient_max) + 1; + vehicle_cost_coefficients_[vehicle] = random_generator.Next(cost_coefficient_max) + 1; } } @@ -219,55 +212,50 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { /// Solves the current routing problem. /// private void Solve(int number_of_orders, int number_of_vehicles) { - Console.WriteLine("Creating model with " + number_of_orders + - " orders and " + number_of_vehicles + " vehicles."); + Console.WriteLine("Creating model with " + number_of_orders + " orders and " + + number_of_vehicles + " vehicles."); // Finalizing model int number_of_locations = locations_.Length; - RoutingIndexManager manager = - new RoutingIndexManager(number_of_locations, number_of_vehicles, - vehicle_starts_, vehicle_ends_); + RoutingIndexManager manager = new RoutingIndexManager(number_of_locations, number_of_vehicles, + vehicle_starts_, vehicle_ends_); RoutingModel model = new RoutingModel(manager); // Setting up dimensions const int big_number = 100000; Manhattan manhattan_callback = new Manhattan(manager, locations_, 1); - model.AddDimension(model.RegisterTransitCallback(manhattan_callback.Call), - big_number, big_number, false, "time"); + model.AddDimension(model.RegisterTransitCallback(manhattan_callback.Call), big_number, + big_number, false, "time"); RoutingDimension time_dimension = model.GetDimensionOrDie("time"); Demand demand_callback = new Demand(manager, order_demands_); - model.AddDimension(model.RegisterUnaryTransitCallback(demand_callback.Call), - 0, vehicle_capacity_, true, "capacity"); + model.AddDimension(model.RegisterUnaryTransitCallback(demand_callback.Call), 0, + vehicle_capacity_, true, "capacity"); RoutingDimension capacity_dimension = model.GetDimensionOrDie("capacity"); // Setting up vehicles Manhattan[] cost_callbacks = new Manhattan[number_of_vehicles]; for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { int cost_coefficient = vehicle_cost_coefficients_[vehicle]; - Manhattan manhattan_cost_callback = - new Manhattan(manager, locations_, cost_coefficient); + Manhattan manhattan_cost_callback = new Manhattan(manager, locations_, cost_coefficient); cost_callbacks[vehicle] = manhattan_cost_callback; - int manhattan_cost_index = - model.RegisterTransitCallback(manhattan_cost_callback.Call); + int manhattan_cost_index = model.RegisterTransitCallback(manhattan_cost_callback.Call); model.SetArcCostEvaluatorOfVehicle(manhattan_cost_index, vehicle); - time_dimension.CumulVar(model.End(vehicle)) - .SetMax(vehicle_end_time_[vehicle]); + time_dimension.CumulVar(model.End(vehicle)).SetMax(vehicle_end_time_[vehicle]); } // Setting up orders for (int order = 0; order < number_of_orders; ++order) { time_dimension.CumulVar(order).SetRange(order_time_windows_[order].start_, order_time_windows_[order].end_); - long[] orders = {manager.NodeToIndex(order)}; + long[] orders = { manager.NodeToIndex(order) }; model.AddDisjunction(orders, order_penalties_[order]); } // Solving RoutingSearchParameters search_parameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - search_parameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.AllUnperformed; + search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.AllUnperformed; Console.WriteLine("Search..."); Assignment solution = model.SolveWithParameters(search_parameters); @@ -291,18 +279,16 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { if (model.IsEnd(solution.Value(model.NextVar(order)))) { route += "Empty"; } else { - for (; !model.IsEnd(order); - order = solution.Value(model.NextVar(order))) { + for (; !model.IsEnd(order); order = solution.Value(model.NextVar(order))) { IntVar local_load = capacity_dimension.CumulVar(order); IntVar local_time = time_dimension.CumulVar(order); - route += order + " Load(" + solution.Value(local_load) + ") " + - "Time(" + solution.Min(local_time) + ", " + - solution.Max(local_time) + ") -> "; + route += order + " Load(" + solution.Value(local_load) + ") " + "Time(" + + solution.Min(local_time) + ", " + solution.Max(local_time) + ") -> "; } IntVar load = capacity_dimension.CumulVar(order); IntVar time = time_dimension.CumulVar(order); - route += order + " Load(" + solution.Value(load) + ") " + "Time(" + - solution.Min(time) + ", " + solution.Max(time) + ")"; + route += order + " Load(" + solution.Value(load) + ") " + "Time(" + solution.Min(time) + + ", " + solution.Max(time) + ")"; } output += route + "\n"; } @@ -327,11 +313,9 @@ public class CapacitatedVehicleRoutingProblemWithTimeWindows { int vehicles = 20; int capacity = 50; - problem.BuildOrders(orders, vehicles, x_max, y_max, demand_max, - time_window_max, time_window_width, penalty_min, - penalty_max); - problem.BuildFleet(orders, vehicles, x_max, y_max, end_time, capacity, - cost_coefficient_max); + problem.BuildOrders(orders, vehicles, x_max, y_max, demand_max, time_window_max, + time_window_width, penalty_min, penalty_max); + problem.BuildFleet(orders, vehicles, x_max, y_max, end_time, capacity, cost_coefficient_max); problem.Solve(orders, vehicles); } } diff --git a/examples/dotnet/csflow.cs b/examples/dotnet/csflow.cs index e732969b89..0f38c51cf3 100644 --- a/examples/dotnet/csflow.cs +++ b/examples/dotnet/csflow.cs @@ -19,35 +19,32 @@ public class CsFlow { Console.WriteLine("Max Flow Problem"); int numNodes = 6; int numArcs = 9; - int[] tails = {0, 0, 0, 0, 1, 2, 3, 3, 4}; - int[] heads = {1, 2, 3, 4, 3, 4, 4, 5, 5}; - int[] capacities = {5, 8, 5, 3, 4, 5, 6, 6, 4}; - int[] expectedFlows = {4, 4, 2, 0, 4, 4, 0, 6, 4}; + int[] tails = { 0, 0, 0, 0, 1, 2, 3, 3, 4 }; + int[] heads = { 1, 2, 3, 4, 3, 4, 4, 5, 5 }; + int[] capacities = { 5, 8, 5, 3, 4, 5, 6, 6, 4 }; + int[] expectedFlows = { 4, 4, 2, 0, 4, 4, 0, 6, 4 }; int expectedTotalFlow = 10; MaxFlow maxFlow = new MaxFlow(); for (int i = 0; i < numArcs; ++i) { int arc = maxFlow.AddArcWithCapacity(tails[i], heads[i], capacities[i]); - if (arc != i) throw new Exception("Internal error"); + if (arc != i) + throw new Exception("Internal error"); } int source = 0; int sink = numNodes - 1; - Console.WriteLine("Solving max flow with " + numNodes + " nodes, and " + - numArcs + " arcs, source=" + source + ", sink=" + sink); + Console.WriteLine("Solving max flow with " + numNodes + " nodes, and " + numArcs + + " arcs, source=" + source + ", sink=" + sink); MaxFlow.Status solveStatus = maxFlow.Solve(source, sink); if (solveStatus == MaxFlow.Status.OPTIMAL) { long totalFlow = maxFlow.OptimalFlow(); - Console.WriteLine("total computed flow " + totalFlow + - ", expected = " + expectedTotalFlow); + Console.WriteLine("total computed flow " + totalFlow + ", expected = " + expectedTotalFlow); for (int i = 0; i < numArcs; ++i) { - Console.WriteLine("Arc " + i + " (" + maxFlow.Head(i) + " -> " + - maxFlow.Tail(i) + + Console.WriteLine("Arc " + i + " (" + maxFlow.Head(i) + " -> " + maxFlow.Tail(i) + "), capacity = " + maxFlow.Capacity(i) + - ") computed = " + maxFlow.Flow(i) + - ", expected = " + expectedFlows[i]); + ") computed = " + maxFlow.Flow(i) + ", expected = " + expectedFlows[i]); } } else { - Console.WriteLine("Solving the max flow problem failed. Solver status: " + - solveStatus); + Console.WriteLine("Solving the max flow problem failed. Solver status: " + solveStatus); } } @@ -55,17 +52,16 @@ public class CsFlow { Console.WriteLine("Min Cost Flow Problem"); int numSources = 4; int numTargets = 4; - int[, ] costs = {{90, 75, 75, 80}, - {35, 85, 55, 65}, - {125, 95, 90, 105}, - {45, 110, 95, 115}}; + int[,] costs = { + { 90, 75, 75, 80 }, { 35, 85, 55, 65 }, { 125, 95, 90, 105 }, { 45, 110, 95, 115 } + }; int expectedCost = 275; MinCostFlow minCostFlow = new MinCostFlow(); for (int source = 0; source < numSources; ++source) { for (int target = 0; target < numTargets; ++target) { - minCostFlow.AddArcWithCapacityAndUnitCost( - source, /*target=*/numSources + target, /*capacity=*/1, - /*flow unit cost=*/costs[source, target]); + minCostFlow.AddArcWithCapacityAndUnitCost(source, /*target=*/numSources + target, + /*capacity=*/1, + /*flow unit cost=*/costs[source, target]); } } for (int source = 0; source < numSources; ++source) { @@ -74,13 +70,12 @@ public class CsFlow { for (int target = 0; target < numTargets; ++target) { minCostFlow.SetNodeSupply(numSources + target, -1); } - Console.WriteLine("Solving min cost flow with " + numSources + - " sources, and " + numTargets + " targets."); + Console.WriteLine("Solving min cost flow with " + numSources + " sources, and " + numTargets + + " targets."); MinCostFlow.Status solveStatus = minCostFlow.Solve(); if (solveStatus == MinCostFlow.Status.OPTIMAL) { - Console.WriteLine( - "total computed flow cost = " + minCostFlow.OptimalCost() + - ", expected = " + expectedCost); + Console.WriteLine("total computed flow cost = " + minCostFlow.OptimalCost() + + ", expected = " + expectedCost); } else { Console.WriteLine("Solving the min cost flow problem failed." + " Solver status: " + solveStatus); diff --git a/examples/dotnet/csintegerprogramming.cs b/examples/dotnet/csintegerprogramming.cs index cbe0bf349f..d144be2692 100644 --- a/examples/dotnet/csintegerprogramming.cs +++ b/examples/dotnet/csintegerprogramming.cs @@ -44,8 +44,7 @@ public class CsIntegerProgramming { return; } - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); // The objective value of the solution. Console.WriteLine("Optimal objective value = " + objective.Value()); @@ -55,12 +54,10 @@ public class CsIntegerProgramming { Console.WriteLine("x2 = " + x2.SolutionValue()); Console.WriteLine("Advanced usage:"); - Console.WriteLine("Problem solved in " + solver.Nodes() + - " branch-and-bound nodes"); + Console.WriteLine("Problem solved in " + solver.Nodes() + " branch-and-bound nodes"); } - private static void RunIntegerProgrammingExampleNaturalApi( - String solverType) { + private static void RunIntegerProgrammingExampleNaturalApi(String solverType) { Solver solver = Solver.CreateSolver(solverType); if (solver == null) { Console.WriteLine("Could not create solver " + solverType); @@ -81,20 +78,17 @@ public class CsIntegerProgramming { return; } - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); // The objective value of the solution. - Console.WriteLine("Optimal objective value = " + - solver.Objective().Value()); + Console.WriteLine("Optimal objective value = " + solver.Objective().Value()); // The value of each variable in the solution. Console.WriteLine("x1 = " + x1.SolutionValue()); Console.WriteLine("x2 = " + x2.SolutionValue()); Console.WriteLine("Advanced usage:"); - Console.WriteLine("Problem solved in " + solver.Nodes() + - " branch-and-bound nodes"); + Console.WriteLine("Problem solved in " + solver.Nodes() + " branch-and-bound nodes"); } static void Main() { @@ -108,20 +102,15 @@ public class CsIntegerProgramming { RunIntegerProgrammingExample("SAT"); Console.WriteLine("---- Linear programming example with GUROBI ----"); RunIntegerProgrammingExample("GUROBI"); - Console.WriteLine( - "---- Integer programming example (Natural API) with GLPK ----"); + Console.WriteLine("---- Integer programming example (Natural API) with GLPK ----"); RunIntegerProgrammingExampleNaturalApi("GLPK"); - Console.WriteLine( - "---- Linear programming example (Natural API) with CBC ----"); + Console.WriteLine("---- Linear programming example (Natural API) with CBC ----"); RunIntegerProgrammingExampleNaturalApi("CBC"); - Console.WriteLine( - "---- Linear programming example (Natural API) with SCIP ----"); + Console.WriteLine("---- Linear programming example (Natural API) with SCIP ----"); RunIntegerProgrammingExampleNaturalApi("SCIP"); - Console.WriteLine( - "---- Linear programming example (Natural API) with SAT ----"); + Console.WriteLine("---- Linear programming example (Natural API) with SAT ----"); RunIntegerProgrammingExampleNaturalApi("SAT"); - Console.WriteLine( - "---- Linear programming example (Natural API) with GUROBI ----"); + Console.WriteLine("---- Linear programming example (Natural API) with GUROBI ----"); RunIntegerProgrammingExampleNaturalApi("GUROBI"); } } diff --git a/examples/dotnet/csknapsack.cs b/examples/dotnet/csknapsack.cs index a23514629a..2a343ed8c1 100644 --- a/examples/dotnet/csknapsack.cs +++ b/examples/dotnet/csknapsack.cs @@ -16,31 +16,26 @@ using Google.OrTools.Algorithms; public class CsKnapsack { static void Main() { - KnapsackSolver solver = - new KnapsackSolver(KnapsackSolver.SolverType - .KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, - "test"); - long[] profits = {360, 83, 59, 130, 431, 67, 230, 52, 93, 125, - 670, 892, 600, 38, 48, 147, 78, 256, 63, 17, - 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, - 514, 28, 87, 73, 78, 15, 26, 78, 210, 36, - 85, 189, 274, 43, 33, 10, 19, 389, 276, 312}; + KnapsackSolver solver = new KnapsackSolver( + KnapsackSolver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "test"); + long[] profits = { 360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, + 38, 48, 147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, + 22, 42, 50, 323, 514, 28, 87, 73, 78, 15, 26, 78, 210, + 36, 85, 189, 274, 43, 33, 10, 19, 389, 276, 312 }; - long[, ] weights = {{7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, - 36, 3, 8, 15, 42, 9, 0, 42, 47, 52, 32, 26, 48, - 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71, - 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13}}; + long[,] weights = { { 7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, + 42, 9, 0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, + 7, 29, 93, 44, 71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13 } }; - long[] capacities = {850}; + long[] capacities = { 850 }; long optimalProfit = 7534; - Console.WriteLine("Solving knapsack with " + profits.Length + - " items, and " + weights.GetLength(0) + " dimension"); + Console.WriteLine("Solving knapsack with " + profits.Length + " items, and " + + weights.GetLength(0) + " dimension"); solver.Init(profits, weights, capacities); long computedProfit = solver.Solve(); - Console.WriteLine("Optimal Profit = " + computedProfit + - ", expected = " + optimalProfit); + Console.WriteLine("Optimal Profit = " + computedProfit + ", expected = " + optimalProfit); } } diff --git a/examples/dotnet/cslinearprogramming.cs b/examples/dotnet/cslinearprogramming.cs index a55945b7f1..2e321315a8 100644 --- a/examples/dotnet/cslinearprogramming.cs +++ b/examples/dotnet/cslinearprogramming.cs @@ -16,8 +16,7 @@ using Google.OrTools.LinearSolver; public class CsLinearProgramming { private static void RunLinearProgrammingExample(String solverType) { - Console.WriteLine( - $"---- Linear programming example with {solverType} ----"); + Console.WriteLine($"---- Linear programming example with {solverType} ----"); Solver solver = Solver.CreateSolver(solverType); if (solver == null) { @@ -65,12 +64,10 @@ public class CsLinearProgramming { return; } - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); // The objective value of the solution. - Console.WriteLine("Optimal objective value = " + - solver.Objective().Value()); + Console.WriteLine("Optimal objective value = " + solver.Objective().Value()); // The value of each variable in the solution. Console.WriteLine("x1 = " + x1.SolutionValue()); @@ -80,8 +77,7 @@ public class CsLinearProgramming { Console.WriteLine("Advanced usage:"); double[] activities = solver.ComputeConstraintActivities(); - Console.WriteLine("Problem solved in " + solver.Iterations() + - " iterations"); + Console.WriteLine("Problem solved in " + solver.Iterations() + " iterations"); Console.WriteLine("x1: reduced cost = " + x1.ReducedCost()); Console.WriteLine("x2: reduced cost = " + x2.ReducedCost()); Console.WriteLine("x3: reduced cost = " + x3.ReducedCost()); @@ -93,10 +89,8 @@ public class CsLinearProgramming { Console.WriteLine(" activity = " + activities[c2.Index()]); } - private static void RunLinearProgrammingExampleNaturalApi(String solverType, - bool printModel) { - Console.WriteLine( - $"---- Linear programming example (Natural API) with {solverType} ----"); + private static void RunLinearProgrammingExampleNaturalApi(String solverType, bool printModel) { + Console.WriteLine($"---- Linear programming example (Natural API) with {solverType} ----"); Solver solver = Solver.CreateSolver(solverType); if (solver == null) { @@ -129,12 +123,10 @@ public class CsLinearProgramming { return; } - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); // The objective value of the solution. - Console.WriteLine("Optimal objective value = " + - solver.Objective().Value()); + Console.WriteLine("Optimal objective value = " + solver.Objective().Value()); // The value of each variable in the solution. Console.WriteLine("x1 = " + x1.SolutionValue()); @@ -143,8 +135,7 @@ public class CsLinearProgramming { Console.WriteLine("Advanced usage:"); double[] activities = solver.ComputeConstraintActivities(); - Console.WriteLine("Problem solved in " + solver.Iterations() + - " iterations"); + Console.WriteLine("Problem solved in " + solver.Iterations() + " iterations"); Console.WriteLine("x1: reduced cost = " + x1.ReducedCost()); Console.WriteLine("x2: reduced cost = " + x2.ReducedCost()); Console.WriteLine("x3: reduced cost = " + x3.ReducedCost()); diff --git a/examples/dotnet/csls_api.cs b/examples/dotnet/csls_api.cs index c0c82c4f70..60341e0463 100644 --- a/examples/dotnet/csls_api.cs +++ b/examples/dotnet/csls_api.cs @@ -21,7 +21,9 @@ using Google.OrTools.ConstraintSolver; public class OneVarLns : BaseLns { public OneVarLns(IntVar[] vars) : base(vars) {} - public override void InitFragments() { index_ = 0; } + public override void InitFragments() { + index_ = 0; + } public override bool NextFragment() { int size = Size(); @@ -62,7 +64,9 @@ class MoveOneVar : IntVarLocalSearchOperator { }; public class SumFilter : IntVarLocalSearchFilter { - public SumFilter(IntVar[] vars) : base(vars) { sum_ = 0; } + public SumFilter(IntVar[] vars) : base(vars) { + sum_ = 0; + } protected override void OnSynchronize(Assignment delta) { sum_ = 0; @@ -72,8 +76,7 @@ public class SumFilter : IntVarLocalSearchFilter { } public override bool Accept(Assignment delta, Assignment unused_deltadelta, - long unused_objective_min, - long unused_objective_max) { + long unused_objective_min, long unused_objective_max) { AssignmentIntContainer solution_delta = delta.IntVarContainer(); int solution_delta_size = solution_delta.Size(); @@ -102,8 +105,8 @@ public class CsLsApi { IntVar[] vars = solver.MakeIntVarArray(4, 0, 4, "vars"); IntVar sum_var = vars.Sum().Var(); OptimizeVar obj = sum_var.Minimize(1); - DecisionBuilder db = solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); OneVarLns one_var_lns = new OneVarLns(vars); LocalSearchPhaseParameters ls_params = solver.MakeLocalSearchPhaseParameters(sum_var, one_var_lns, db); @@ -121,8 +124,8 @@ public class CsLsApi { IntVar[] vars = solver.MakeIntVarArray(4, 0, 4, "vars"); IntVar sum_var = vars.Sum().Var(); OptimizeVar obj = sum_var.Minimize(1); - DecisionBuilder db = solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); MoveOneVar move_one_var = new MoveOneVar(vars); LocalSearchPhaseParameters ls_params = solver.MakeLocalSearchPhaseParameters(sum_var, move_one_var, db); @@ -140,16 +143,14 @@ public class CsLsApi { IntVar[] vars = solver.MakeIntVarArray(4, 0, 4, "vars"); IntVar sum_var = vars.Sum().Var(); OptimizeVar obj = sum_var.Minimize(1); - DecisionBuilder db = solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MAX_VALUE); + DecisionBuilder db = + solver.MakePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE); MoveOneVar move_one_var = new MoveOneVar(vars); SumFilter filter = new SumFilter(vars); - IntVarLocalSearchFilter[] filters = new IntVarLocalSearchFilter[]{filter}; - LocalSearchFilterManager filter_manager = - new LocalSearchFilterManager(filters); + IntVarLocalSearchFilter[] filters = new IntVarLocalSearchFilter[] { filter }; + LocalSearchFilterManager filter_manager = new LocalSearchFilterManager(filters); LocalSearchPhaseParameters ls_params = - solver.MakeLocalSearchPhaseParameters(sum_var, move_one_var, db, null, - filter_manager); + solver.MakeLocalSearchPhaseParameters(sum_var, move_one_var, db, null, filter_manager); DecisionBuilder ls = solver.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector collector = solver.MakeLastSolutionCollector(); collector.AddObjective(sum_var); diff --git a/examples/dotnet/csrabbitspheasants.cs b/examples/dotnet/csrabbitspheasants.cs index 3a0ffeae39..ed68598114 100644 --- a/examples/dotnet/csrabbitspheasants.cs +++ b/examples/dotnet/csrabbitspheasants.cs @@ -18,7 +18,9 @@ using Google.OrTools.ConstraintSolver; * Shows how to write a custom decision builder. */ public class AssignFirstUnboundToMin : NetDecisionBuilder { - public AssignFirstUnboundToMin(IntVar[] vars) { vars_ = vars; } + public AssignFirstUnboundToMin(IntVar[] vars) { + vars_ = vars; + } public override Decision Next(Solver solver) { foreach (IntVar var in vars_) { @@ -44,17 +46,17 @@ public class CsRabbitsPheasants { IntVar pheasants = solver.MakeIntVar(0, 100, "pheasants"); solver.Add(rabbits + pheasants == 20); solver.Add(rabbits * 4 + pheasants * 2 == 56); - DecisionBuilder db = - new AssignFirstUnboundToMin(new IntVar[]{rabbits, pheasants}); + DecisionBuilder db = new AssignFirstUnboundToMin(new IntVar[] { rabbits, pheasants }); solver.NewSearch(db); solver.NextSolution(); - Console.WriteLine( - "Solved Rabbits + Pheasants in {0} ms, and {1} search tree branches.", - solver.WallTime(), solver.Branches()); + Console.WriteLine("Solved Rabbits + Pheasants in {0} ms, and {1} search tree branches.", + solver.WallTime(), solver.Branches()); Console.WriteLine(rabbits.ToString()); Console.WriteLine(pheasants.ToString()); solver.EndSearch(); } - public static void Main(String[] args) { Solve(); } + public static void Main(String[] args) { + Solve(); + } } diff --git a/examples/dotnet/cstsp.cs b/examples/dotnet/cstsp.cs index f48dd50656..6bb66c8651 100644 --- a/examples/dotnet/cstsp.cs +++ b/examples/dotnet/cstsp.cs @@ -49,8 +49,7 @@ class Tsp { // has the following signature: ResultCallback2. // The two arguments are the from and to node inidices. RandomManhattan distances = new RandomManhattan(manager, size, seed); - routing.SetArcCostEvaluatorOfAllVehicles( - routing.RegisterTransitCallback(distances.Call)); + routing.SetArcCostEvaluatorOfAllVehicles(routing.RegisterTransitCallback(distances.Call)); // Forbid node connections (randomly). Random randomizer = new Random(); @@ -66,16 +65,14 @@ class Tsp { } // Add dummy dimension to test API. - routing.AddDimension( - routing.RegisterUnaryTransitCallback((long index) => { return 1; }), - size + 1, size + 1, true, "dummy"); + routing.AddDimension(routing.RegisterUnaryTransitCallback((long index) => { return 1; }), + size + 1, size + 1, true, "dummy"); // Solve, returns a solution if any (owned by RoutingModel). RoutingSearchParameters search_parameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); // Setting first solution heuristic (cheapest addition). - search_parameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(search_parameters); Console.WriteLine("Status = {0}", routing.GetStatus()); diff --git a/examples/tests/ConstraintSolverTests.cs b/examples/tests/ConstraintSolverTests.cs index 11e1c69996..bff01ddea3 100644 --- a/examples/tests/ConstraintSolverTests.cs +++ b/examples/tests/ConstraintSolverTests.cs @@ -1,14 +1,26 @@ +// Copyright 2010-2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + using System; using Xunit; using Google.OrTools.ConstraintSolver; -using static Google.OrTools.ConstraintSolver - .operations_research_constraint_solver; +using static Google.OrTools.ConstraintSolver.operations_research_constraint_solver; namespace Google.OrTools.Tests { public class ConstraintSolverTest { [Fact] public void IntVectorToInt64Vector() { - int[] input = {5, 11, 17}; + int[] input = { 5, 11, 17 }; long[] output = ToInt64Vector(input); Assert.Equal(3, output.Length); Assert.Equal(5, output[0]); @@ -228,61 +240,43 @@ namespace Google.OrTools.Tests { // Arithmetic operator with an IntExpr IntExpr e11a = c1 + (y == 11); - Assert.Equal("(Watch(0 .. 1) + Watch(0 .. 1))", - e11a.ToString()); + Assert.Equal("(Watch(0 .. 1) + Watch(0 .. 1))", e11a.ToString()); IntExpr e11b = (y == 11) + c1; - Assert.Equal("(Watch(0 .. 1) + Watch(0 .. 1))", - e11b.ToString()); + Assert.Equal("(Watch(0 .. 1) + Watch(0 .. 1))", e11b.ToString()); IntExpr e11c = c1 - (y == 11); - Assert.Equal("(Watch(0 .. 1) - Watch(0 .. 1))", - e11c.ToString()); + Assert.Equal("(Watch(0 .. 1) - Watch(0 .. 1))", e11c.ToString()); IntExpr e11d = (y == 11) - c1; - Assert.Equal("(Watch(0 .. 1) - Watch(0 .. 1))", - e11d.ToString()); + Assert.Equal("(Watch(0 .. 1) - Watch(0 .. 1))", e11d.ToString()); IntExpr e11e = c1 * (y == 11); - Assert.Equal("(Watch(0 .. 1) * Watch(0 .. 1))", - e11e.ToString()); + Assert.Equal("(Watch(0 .. 1) * Watch(0 .. 1))", e11e.ToString()); IntExpr e11f = (y == 11) * c1; - Assert.Equal("(Watch(0 .. 1) * Watch(0 .. 1))", - e11f.ToString()); + Assert.Equal("(Watch(0 .. 1) * Watch(0 .. 1))", e11f.ToString()); // Relational operator with an IntExpr Constraint c12a = c1 == (y == 11); - Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", - c12a.ToString()); + Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", c12a.ToString()); Constraint c12b = (y == 11) == c1; - Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", - c12b.ToString()); + Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", c12b.ToString()); Constraint c12c = c1 != (y == 11); - Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", - c12c.ToString()); + Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", c12c.ToString()); Constraint c12d = (y == 11) != c1; - Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", - c12d.ToString()); + Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", c12d.ToString()); Constraint c12e = c1 >= (y == 11); - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c12e.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c12e.ToString()); Constraint c12f = (y == 11) >= c1; - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c12f.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c12f.ToString()); Constraint c12g = c1 > (y == 11); - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c12g.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c12g.ToString()); Constraint c12h = (y == 11) > c1; - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c12h.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c12h.ToString()); Constraint c12i = c1 <= (y == 11); - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c12i.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c12i.ToString()); Constraint c12j = (y == 11) <= c1; - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c12j.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c12j.ToString()); Constraint c12k = c1 < (y == 11); - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c12k.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c12k.ToString()); Constraint c12l = (y == 11) < c1; - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c12l.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c12l.ToString()); } [Fact] @@ -302,26 +296,20 @@ namespace Google.OrTools.Tests { // Relational operator with a Constraint Constraint c10a = c1 == c2; - Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", - c10a.ToString()); + Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", c10a.ToString()); Constraint c10b = c1 != c2; - Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", - c10b.ToString()); + Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", c10b.ToString()); Constraint c10c = c1 <= c2; - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c10c.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c10c.ToString()); Constraint c10d = c1 >= c2; - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c10d.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c10d.ToString()); Constraint c10e = c1 > c2; - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c10e.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c10e.ToString()); Constraint c10f = c1 < c2; - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c10f.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c10f.ToString()); } [Fact] @@ -454,26 +442,20 @@ namespace Google.OrTools.Tests { // Relational operator between IntExpr Constraint c10a = (x == 7) == (y == 11); - Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", - c10a.ToString()); + Assert.Equal("Watch(0 .. 1) == Watch(0 .. 1)", c10a.ToString()); Constraint c10b = (x == 7) != (y == 11); - Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", - c10b.ToString()); + Assert.Equal("Watch(0 .. 1) != Watch(0 .. 1)", c10b.ToString()); Constraint c10c = (x == 7) <= (y == 11); - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c10c.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c10c.ToString()); Constraint c10d = (x == 7) >= (y == 11); - Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", - c10d.ToString()); + Assert.Equal("Watch(0 .. 1) <= Watch(0 .. 1)", c10d.ToString()); Constraint c10e = (x == 7) > (y == 11); - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c10e.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c10e.ToString()); Constraint c10f = (x == 7) < (y == 11); - Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", - c10f.ToString()); + Assert.Equal("Watch(0 .. 1) < Watch(0 .. 1)", c10f.ToString()); } [Fact] @@ -603,26 +585,20 @@ namespace Google.OrTools.Tests { // Relational operator between IntExpr Constraint c10a = (x >= 7) == (y >= 11); - Assert.Equal("Watch= 7>(0 .. 1) == Watch= 11>(0 .. 1)", - c10a.ToString()); + Assert.Equal("Watch= 7>(0 .. 1) == Watch= 11>(0 .. 1)", c10a.ToString()); Constraint c10b = (x >= 7) != (y >= 11); - Assert.Equal("Watch= 7>(0 .. 1) != Watch= 11>(0 .. 1)", - c10b.ToString()); + Assert.Equal("Watch= 7>(0 .. 1) != Watch= 11>(0 .. 1)", c10b.ToString()); Constraint c10c = (x >= 7) <= (y >= 11); - Assert.Equal("Watch= 7>(0 .. 1) <= Watch= 11>(0 .. 1)", - c10c.ToString()); + Assert.Equal("Watch= 7>(0 .. 1) <= Watch= 11>(0 .. 1)", c10c.ToString()); Constraint c10d = (x >= 7) >= (y >= 11); - Assert.Equal("Watch= 11>(0 .. 1) <= Watch= 7>(0 .. 1)", - c10d.ToString()); + Assert.Equal("Watch= 11>(0 .. 1) <= Watch= 7>(0 .. 1)", c10d.ToString()); Constraint c10e = (x >= 7) > (y >= 11); - Assert.Equal("Watch= 11>(0 .. 1) < Watch= 7>(0 .. 1)", - c10e.ToString()); + Assert.Equal("Watch= 11>(0 .. 1) < Watch= 7>(0 .. 1)", c10e.ToString()); Constraint c10f = (x >= 7) < (y >= 11); - Assert.Equal("Watch= 7>(0 .. 1) < Watch= 11>(0 .. 1)", - c10f.ToString()); + Assert.Equal("Watch= 7>(0 .. 1) < Watch= 11>(0 .. 1)", c10f.ToString()); } [Fact] @@ -643,7 +619,7 @@ namespace Google.OrTools.Tests { SequenceVar var = disjunctive.SequenceVar(); Assignment ass = solver.MakeAssignment(); ass.Add(var); - ass.SetForwardSequence(var, new int[]{1, 3, 5}); + ass.SetForwardSequence(var, new int[] { 1, 3, 5 }); int[] seq = ass.ForwardSequence(var); Assert.Equal(3, seq.Length); Assert.Equal(1, seq[0]); @@ -654,15 +630,19 @@ namespace Google.OrTools.Tests { // A simple demon that simply sets the maximum of a fixed IntVar to 10 when // it's being called. class SetMaxDemon : NetDemon { - public SetMaxDemon(IntVar x) { x_ = x; } - public override void Run(Solver s) { x_.SetMax(10); } + public SetMaxDemon(IntVar x) { + x_ = x; + } + public override void Run(Solver s) { + x_.SetMax(10); + } private IntVar x_; } [Fact] public void Demon() { Solver solver = new Solver("DemonTest"); - IntVar x = solver.MakeIntVar(new int[]{2, 4, -1, 6, 11, 10}, "x"); + IntVar x = solver.MakeIntVar(new int[] { 2, 4, -1, 6, 11, 10 }, "x"); NetDemon demon = new SetMaxDemon(x); Assert.Equal(11, x.Max()); demon.Run(solver); @@ -681,7 +661,9 @@ namespace Google.OrTools.Tests { demon_ = new SetMaxDemon(x_); x_.WhenBound(demon_); } - public override void InitialPropagate() { x_.SetMin(5); } + public override void InitialPropagate() { + x_.SetMin(5); + } private IntVar x_; private Demon demon_; } @@ -689,11 +671,11 @@ namespace Google.OrTools.Tests { [Fact] public void MinAndMaxConstraint() { Solver solver = new Solver("TestConstraint"); - IntVar x = solver.MakeIntVar(new int[]{2, 4, -1, 6, 11, 10}, "x"); + IntVar x = solver.MakeIntVar(new int[] { 2, 4, -1, 6, 11, 10 }, "x"); Constraint ct = new SetMinAndMaxConstraint(solver, x); solver.Add(ct); - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); Assert.Equal(-1, x.Min()); Assert.Equal(11, x.Max()); @@ -735,11 +717,11 @@ namespace Google.OrTools.Tests { [Fact] public void FailingConstraint() { Solver solver = new Solver("TestConstraint"); - IntVar x = solver.MakeIntVar(new int[]{2, 4, -1, 6, 11, 10}, "x"); + IntVar x = solver.MakeIntVar(new int[] { 2, 4, -1, 6, 11, 10 }, "x"); Constraint ct = new DumbGreaterOrEqualToFive(solver, x); solver.Add(ct); - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); Assert.True(solver.NextSolution()); Assert.Equal(6, x.Min()); @@ -749,7 +731,7 @@ namespace Google.OrTools.Tests { [Fact] public void DomainIterator() { Solver solver = new Solver("TestConstraint"); - IntVar x = solver.MakeIntVar(new int[]{2, 4, -1, 6, 11, 10}, "x"); + IntVar x = solver.MakeIntVar(new int[] { 2, 4, -1, 6, 11, 10 }, "x"); ulong count = 0; foreach (long value in x.GetDomain()) { count++; @@ -767,7 +749,9 @@ namespace Google.OrTools.Tests { count_++; } } - public int count() { return count_; } + public int count() { + return count_; + } private IntVar x_; private int count_; } @@ -781,9 +765,11 @@ namespace Google.OrTools.Tests { x_.WhenDomain(demon_); } public override void InitialPropagate() { - x_.RemoveValues(new long[]{3, 5, 7}); + x_.RemoveValues(new long[] { 3, 5, 7 }); + } + public int count() { + return demon_.count(); } - public int count() { return demon_.count(); } private IntVar x_; private CountHoles demon_; } @@ -794,8 +780,8 @@ namespace Google.OrTools.Tests { IntVar x = solver.MakeIntVar(0, 10, "x"); RemoveThreeValues ct = new RemoveThreeValues(solver, x); solver.Add(ct); - DecisionBuilder db = solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.Solve(db); Assert.Equal(3, ct.count()); } @@ -830,12 +816,11 @@ namespace Google.OrTools.Tests { IntVar var = solver.MakeIntVar(1, 1, "Variable"); OptimizeVar objective = solver.MakeMinimize(var, 1); int count = 0; - SearchMonitor searchlog = - solver.MakeSearchLog(0, // branch period - () => { - count++; - return "display callback..."; - }); + SearchMonitor searchlog = solver.MakeSearchLog(0, // branch period + () => { + count++; + return "display callback..."; + }); if (callGC) { GC.Collect(); GC.WaitForPendingFinalizers(); @@ -853,13 +838,12 @@ namespace Google.OrTools.Tests { IntVar var = solver.MakeIntVar(1, 1, "Variable"); OptimizeVar objective = solver.MakeMinimize(var, 1); int count = 0; - SearchMonitor searchlog = - solver.MakeSearchLog(0, // branch period - objective, // objective var to monitor - () => { - count++; - return "OptimizeVar display callback"; - }); + SearchMonitor searchlog = solver.MakeSearchLog(0, // branch period + objective, // objective var to monitor + () => { + count++; + return "OptimizeVar display callback"; + }); if (callGC) { GC.Collect(); GC.WaitForPendingFinalizers(); @@ -877,13 +861,12 @@ namespace Google.OrTools.Tests { IntVar var = solver.MakeIntVar(1, 1, "Variable"); OptimizeVar objective = solver.MakeMinimize(var, 1); int count = 0; - SearchMonitor searchlog = - solver.MakeSearchLog(0, // branch period - var, // int var to monitor - () => { - count++; - return "IntVar display callback"; - }); + SearchMonitor searchlog = solver.MakeSearchLog(0, // branch period + var, // int var to monitor + () => { + count++; + return "IntVar display callback"; + }); if (callGC) { GC.Collect(); GC.WaitForPendingFinalizers(); diff --git a/examples/tests/LinearSolverTests.cs b/examples/tests/LinearSolverTests.cs index 36b63452dc..e1bd73d58c 100644 --- a/examples/tests/LinearSolverTests.cs +++ b/examples/tests/LinearSolverTests.cs @@ -1,6 +1,6 @@ using System; -using Google.OrTools.LinearSolver; using Xunit; +using Google.OrTools.LinearSolver; namespace Google.OrTools.Tests { public class LinearSolverTest { @@ -185,7 +185,7 @@ namespace Google.OrTools.Tests { Constraint ct2 = solver.Add(-2 * x.Sum() == 3); Assert.Equal(-2.0, ct2.GetCoefficient(x[0])); - LinearExpr[] array = new LinearExpr[]{x[0] + 2.0, x[0] + 3, x[0] + 4}; + LinearExpr[] array = new LinearExpr[] { x[0] + 2.0, x[0] + 3, x[0] + 4 }; Constraint ct3 = solver.Add(array.Sum() == 1); Assert.Equal(3.0, ct3.GetCoefficient(x[0])); Assert.Equal(-8.0, ct3.Lb()); @@ -215,8 +215,7 @@ namespace Google.OrTools.Tests { Assert.True(solver.Objective().Minimization()); } - void SolveAndPrint(in Solver solver, in Variable[] variables, - in Constraint[] constraints) { + void SolveAndPrint(in Solver solver, in Variable[] variables, in Constraint[] constraints) { Console.WriteLine($"Number of variables = {solver.NumVariables()}"); Console.WriteLine($"Number of constraints = {solver.NumConstraints()}"); @@ -229,14 +228,11 @@ namespace Google.OrTools.Tests { foreach (Variable var in variables) { Console.WriteLine($"{var.Name()} = {var.SolutionValue()}"); } - Console.WriteLine( - $"Optimal objective value = {solver.Objective().Value()}"); + Console.WriteLine($"Optimal objective value = {solver.Objective().Value()}"); Console.WriteLine(""); Console.WriteLine("Advanced usage:"); - Console.WriteLine( - $"Problem solved in {solver.WallTime()} milliseconds"); - Console.WriteLine( - $"Problem solved in {solver.Iterations()} iterations"); + Console.WriteLine($"Problem solved in {solver.WallTime()} milliseconds"); + Console.WriteLine($"Problem solved in {solver.Iterations()} iterations"); foreach (Variable var in variables) { Console.WriteLine($"{var.Name()}: reduced cost {var.ReducedCost()}"); } @@ -250,11 +246,11 @@ namespace Google.OrTools.Tests { } void RunLinearProgrammingExample(in String problemType) { - Console.WriteLine( - $"------ Linear programming example with {problemType} ------"); + Console.WriteLine($"------ Linear programming example with {problemType} ------"); Solver solver = Solver.CreateSolver(problemType); - if (solver == null) return; + if (solver == null) + return; // x and y are continuous non-negative variables. Variable x = solver.MakeNumVar(0.0, double.PositiveInfinity, "x"); @@ -267,8 +263,7 @@ namespace Google.OrTools.Tests { objective.SetMaximization(); // x + 2y <= 14. - Constraint c0 = - solver.MakeConstraint(double.NegativeInfinity, 14.0, "c0"); + Constraint c0 = solver.MakeConstraint(double.NegativeInfinity, 14.0, "c0"); c0.SetCoefficient(x, 1); c0.SetCoefficient(y, 2); @@ -282,14 +277,14 @@ namespace Google.OrTools.Tests { c2.SetCoefficient(x, 1); c2.SetCoefficient(y, -1); - SolveAndPrint(solver, new Variable[]{x, y}, new Constraint[]{c0, c1, c2}); + SolveAndPrint(solver, new Variable[] { x, y }, new Constraint[] { c0, c1, c2 }); } void RunMixedIntegerProgrammingExample(in String problemType) { - Console.WriteLine( - $"------ Mixed integer programming example with {problemType} ------"); + Console.WriteLine($"------ Mixed integer programming example with {problemType} ------"); Solver solver = Solver.CreateSolver(problemType); - if (solver == null) return; + if (solver == null) + return; // x and y are integers non-negative variables. Variable x = solver.MakeIntVar(0.0, double.PositiveInfinity, "x"); @@ -302,8 +297,7 @@ namespace Google.OrTools.Tests { objective.SetMaximization(); // x + 7 * y <= 17.5. - Constraint c0 = - solver.MakeConstraint(double.NegativeInfinity, 17.5, "c0"); + Constraint c0 = solver.MakeConstraint(double.NegativeInfinity, 17.5, "c0"); c0.SetCoefficient(x, 1); c0.SetCoefficient(y, 7); @@ -312,14 +306,14 @@ namespace Google.OrTools.Tests { c1.SetCoefficient(x, 1); c1.SetCoefficient(y, 0); - SolveAndPrint(solver, new Variable[]{x, y}, new Constraint[]{c0, c1}); + SolveAndPrint(solver, new Variable[] { x, y }, new Constraint[] { c0, c1 }); } void RunBooleanProgrammingExample(in String problemType) { - Console.WriteLine( - $"------ Boolean programming example with {problemType} ------"); + Console.WriteLine($"------ Boolean programming example with {problemType} ------"); Solver solver = Solver.CreateSolver(problemType); - if (solver == null) return; + if (solver == null) + return; // x and y are boolean variables. Variable x = solver.MakeBoolVar("x"); @@ -336,7 +330,7 @@ namespace Google.OrTools.Tests { c0.SetCoefficient(x, 1); c0.SetCoefficient(y, 2); - SolveAndPrint(solver, new Variable[]{x, y}, new Constraint[]{c0}); + SolveAndPrint(solver, new Variable[] { x, y }, new Constraint[] { c0 }); } [Fact] @@ -370,8 +364,7 @@ namespace Google.OrTools.Tests { objective.SetMaximization(); // x + 7 * y <= 17.5. - Constraint c0 = - solver.MakeConstraint(double.NegativeInfinity, 17.5, "c0"); + Constraint c0 = solver.MakeConstraint(double.NegativeInfinity, 17.5, "c0"); c0.SetCoefficient(x, 1); c0.SetCoefficient(y, 7); @@ -385,7 +378,7 @@ namespace Google.OrTools.Tests { Variable[] variables = solver.variables(); Assert.Equal(variables.Length, 2); - solver.SetHint(new Variable[]{x, y}, new double[]{2.0, 3.0}); + solver.SetHint(new Variable[] { x, y }, new double[] { 2.0, 3.0 }); } } -} // namespace Google.OrTools.Tests \ No newline at end of file +} // namespace Google.OrTools.Tests diff --git a/examples/tests/RoutingSolverTests.cs b/examples/tests/RoutingSolverTests.cs index 1de7acee63..59c421dc58 100644 --- a/examples/tests/RoutingSolverTests.cs +++ b/examples/tests/RoutingSolverTests.cs @@ -14,13 +14,12 @@ namespace Google.OrTools.Tests { // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create a distance callback. - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return Math.Abs(toNode - fromNode); - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return Math.Abs(toNode - fromNode); + }); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); if (callGC) { @@ -28,10 +27,8 @@ namespace Google.OrTools.Tests { } // Setting first solution heuristic. RoutingSearchParameters searchParameters = - operations_research_constraint_solver - .DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + operations_research_constraint_solver.DefaultRoutingSearchParameters(); + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(searchParameters); // 0 --(+1)-> 1 --(+1)-> 2 --(+1)-> 3 --(+1)-> 4 --(+4)-> 0 := +8 Assert.Equal(8, solution.ObjectiveValue()); diff --git a/examples/tests/SatSolverTests.cs b/examples/tests/SatSolverTests.cs index 6cf78dc484..8abea70981 100644 --- a/examples/tests/SatSolverTests.cs +++ b/examples/tests/SatSolverTests.cs @@ -12,8 +12,7 @@ namespace Google.OrTools.Tests { return var; } - static ConstraintProto NewLinear2(int v1, int v2, long c1, long c2, long lb, - long ub) { + static ConstraintProto NewLinear2(int v1, int v2, long c1, long c2, long lb, long ub) { LinearConstraintProto linear = new LinearConstraintProto(); linear.Vars.Add(v1); linear.Vars.Add(v2); @@ -26,8 +25,8 @@ namespace Google.OrTools.Tests { return ct; } - static ConstraintProto NewLinear3(int v1, int v2, int v3, long c1, long c2, - long c3, long lb, long ub) { + static ConstraintProto NewLinear3(int v1, int v2, int v3, long c1, long c2, long c3, long lb, + long ub) { LinearConstraintProto linear = new LinearConstraintProto(); linear.Vars.Add(v1); linear.Vars.Add(v2); @@ -82,7 +81,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = SatHelper.Solve(model); Assert.Equal(CpSolverStatus.Optimal, response.Status); Assert.Equal(30, response.ObjectiveValue); - Assert.Equal(new long[]{10, 10, 30}, response.Solution); + Assert.Equal(new long[] { 10, 10, 30 }, response.Solution); // Console.WriteLine("response = " + response.ToString()); } @@ -98,7 +97,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = SatHelper.Solve(model); Assert.Equal(CpSolverStatus.Optimal, response.Status); Assert.Equal(30, response.ObjectiveValue); - Assert.Equal(new long[]{10, -10}, response.Solution); + Assert.Equal(new long[] { 10, -10 }, response.Solution); // Console.WriteLine("response = " + response.ToString()); } @@ -112,7 +111,7 @@ namespace Google.OrTools.Tests { model.AddLinearConstraint(v1 + v2, -1000000, 100000); model.AddLinearConstraint(v1 + 2 * v2 - v3, 0, 100000); model.Maximize(v3); - Assert.Equal(v1.Domain.FlattenedIntervals(), new long[]{-10, 10}); + Assert.Equal(v1.Domain.FlattenedIntervals(), new long[] { -10, 10 }); // Console.WriteLine("model = " + model.Model.ToString()); CpSolver solver = new CpSolver(); @@ -121,7 +120,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = solver.Response; Assert.Equal(30, response.ObjectiveValue); - Assert.Equal(new long[]{10, 10, 30}, response.Solution); + Assert.Equal(new long[] { 10, 10, 30 }, response.Solution); // Console.WriteLine("response = " + reponse.ToString()); } @@ -140,7 +139,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = solver.Response; Assert.Equal(30, response.ObjectiveValue); - Assert.Equal(new long[]{10, -10}, response.Solution); + Assert.Equal(new long[] { 10, -10 }, response.Solution); // Console.WriteLine("response = " + reponse.ToString()); } @@ -160,7 +159,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = solver.Response; Assert.Equal(-10, solver.Value(v1)); Assert.Equal(10, solver.Value(v2)); - Assert.Equal(new long[]{-10, 10}, response.Solution); + Assert.Equal(new long[] { -10, 10 }, response.Solution); Assert.Equal(-30, solver.Value(v1 - 2 * v2)); Assert.Equal(-30, response.ObjectiveValue); // Console.WriteLine("response = " + reponse.ToString()); @@ -175,7 +174,7 @@ namespace Google.OrTools.Tests { IntVar squaredDelta = model.NewIntVar(0, 25, "squaredDelta"); model.Add(x == boolvar * 4); model.Add(delta == x - 5); - model.AddProdEquality(squaredDelta, new IntVar[]{delta, delta}); + model.AddProdEquality(squaredDelta, new IntVar[] { delta, delta }); model.Minimize(squaredDelta); // Console.WriteLine("model = " + model.Model.ToString()); @@ -190,7 +189,7 @@ namespace Google.OrTools.Tests { Assert.Equal(4, solver.Value(x)); Assert.Equal(-1, solver.Value(delta)); Assert.Equal(1, solver.Value(squaredDelta)); - Assert.Equal(new long[]{1, 4, -1, 1}, response.Solution); + Assert.Equal(new long[] { 1, 4, -1, 1 }, response.Solution); Assert.Equal(1.0, response.ObjectiveValue, 5); } @@ -204,9 +203,9 @@ namespace Google.OrTools.Tests { model.Add(x == 4).OnlyEnforceIf(boolvar); model.Add(x == 0).OnlyEnforceIf(boolvar.Not()); model.Add(delta == x - 5); - long[, ] tuples = {{-5, 25}, {-4, 16}, {-3, 9}, {-2, 4}, {-1, 1}, {0, 0}, - {1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25}}; - model.AddAllowedAssignments(new IntVar[]{delta, squaredDelta}, tuples); + long[,] tuples = { { -5, 25 }, { -4, 16 }, { -3, 9 }, { -2, 4 }, { -1, 1 }, { 0, 0 }, + { 1, 1 }, { 2, 4 }, { 3, 9 }, { 4, 16 }, { 5, 25 } }; + model.AddAllowedAssignments(new IntVar[] { delta, squaredDelta }, tuples); model.Minimize(squaredDelta); CpSolver solver = new CpSolver(); @@ -217,7 +216,7 @@ namespace Google.OrTools.Tests { Assert.Equal(4, solver.Value(x)); Assert.Equal(-1, solver.Value(delta)); Assert.Equal(1, solver.Value(squaredDelta)); - Assert.Equal(new long[]{1, 4, -1, 1}, response.Solution); + Assert.Equal(new long[] { 1, 4, -1, 1 }, response.Solution); Assert.Equal(1.0, response.ObjectiveValue, 6); } @@ -236,7 +235,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = solver.Response; Assert.Equal(3, solver.Value(v1)); Assert.Equal(1, solver.Value(v2)); - Assert.Equal(new long[]{3, 1, 3}, response.Solution); + Assert.Equal(new long[] { 3, 1, 3 }, response.Solution); Assert.Equal(0, response.ObjectiveValue); // Console.WriteLine("response = " + reponse.ToString()); } @@ -256,7 +255,7 @@ namespace Google.OrTools.Tests { CpSolverResponse response = solver.Response; Assert.Equal(3, solver.Value(v1)); Assert.Equal(4, solver.Value(v2)); - Assert.Equal(new long[]{3, 4, 3}, response.Solution); + Assert.Equal(new long[] { 3, 4, 3 }, response.Solution); Assert.Equal(0, response.ObjectiveValue); // Console.WriteLine("response = " + reponse.ToString()); } diff --git a/examples/tests/issue18.cs b/examples/tests/issue18.cs index 002ea32dd4..ad98bf1756 100644 --- a/examples/tests/issue18.cs +++ b/examples/tests/issue18.cs @@ -30,9 +30,9 @@ namespace Google.OrTools.Tests { IntExpr globalSum = solver.MakeSum(vars.ToArray()); - DecisionBuilder db = solver.MakePhase( - vars.ToArray(), Google.OrTools.ConstraintSolver.Solver.INT_VAR_SIMPLE, - Google.OrTools.ConstraintSolver.Solver.INT_VALUE_SIMPLE); + DecisionBuilder db = + solver.MakePhase(vars.ToArray(), Google.OrTools.ConstraintSolver.Solver.INT_VAR_SIMPLE, + Google.OrTools.ConstraintSolver.Solver.INT_VALUE_SIMPLE); solver.NewSearch(db, new OptimizeVar(solver, true, globalSum.Var(), 100)); diff --git a/examples/tests/issue22.cs b/examples/tests/issue22.cs index 2ca6910bfd..f9b0df4c37 100644 --- a/examples/tests/issue22.cs +++ b/examples/tests/issue22.cs @@ -30,7 +30,7 @@ namespace Google.OrTools.Tests { // IntVar[,] x = solver.MakeIntVarMatrix(2,2, new int[] {-2,0,1,2}, "x"); // this doesn't work - IntVar[, ] x = solver.MakeIntVarMatrix(2, 2, new int[]{0, 1, 2}, "x"); + IntVar[,] x = solver.MakeIntVarMatrix(2, 2, new int[] { 0, 1, 2 }, "x"); for (int w = 0; w < 2; w++) { IntVar[] b = new IntVar[2]; @@ -41,16 +41,15 @@ namespace Google.OrTools.Tests { } IntVar[] x_flat = x.Flatten(); - DecisionBuilder db = solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = + solver.MakePhase(x_flat, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.WriteLine("x: "); for (int j = 0; j < 2; j++) { Console.Write("worker" + (j + 1).ToString() + ":"); for (int i = 0; i < 2; i++) { - Console.Write(" {0,2} ", x [j, i] - .Value()); + Console.Write(" {0,2} ", x[j, i].Value()); } Console.Write("\n"); } diff --git a/examples/tests/issue33.cs b/examples/tests/issue33.cs index 780d46c934..bc727371d1 100644 --- a/examples/tests/issue33.cs +++ b/examples/tests/issue33.cs @@ -24,26 +24,11 @@ using Xunit; namespace Google.OrTools.Test { public class Task { - public int Id { - get; - private set; - } - public int TaskType { - get; - private set; - } - public int LocationId { - get; - private set; - } - public Dictionary Durations { - get; - private set; - } - public int TaskPosition { - get; - private set; - } + public int Id { get; private set; } + public int TaskType { get; private set; } + public int LocationId { get; private set; } + public Dictionary Durations { get; private set; } + public int TaskPosition { get; private set; } public Task(int id, int taskType, int locationIndex, int taskPosition, Dictionary durations) { @@ -64,10 +49,7 @@ namespace Google.OrTools.Test { } public class WorkLocation { - public int Id { - get; - private set; - } + public int Id { get; private set; } public int NbTasks { get { Debug.Assert(Tasks != null); @@ -78,31 +60,18 @@ namespace Google.OrTools.Test { Tasks = new Task[value]; } } - public Task[] Tasks { - get; - private set; - } + public Task[] Tasks { get; private set; } - public WorkLocation(int index) { Id = index; } + public WorkLocation(int index) { + Id = index; + } } public class Tool { - public int Id { - get; - private set; - } - public HashSet TaskTypes { - get; - set; - } - public int[, ] TravellingTime { - get; - set; - } - public int InitialLocationId { - get; - set; - } + public int Id { get; private set; } + public HashSet TaskTypes { get; set; } + public int[,] TravellingTime { get; set; } + public int InitialLocationId { get; set; } public Tool(int index, int initialLocation = 0) { Id = index; @@ -110,7 +79,9 @@ namespace Google.OrTools.Test { TaskTypes = new HashSet(); } - public void AddTaskType(int t) { TaskTypes.Add(t); } + public void AddTaskType(int t) { + TaskTypes.Add(t); + } public bool CanPerformTaskType(int taskType) { return TaskTypes.Contains(taskType); @@ -118,14 +89,8 @@ namespace Google.OrTools.Test { } public class FactoryDescription { - public Tool[] Tools { - get; - private set; - } - public WorkLocation[] Locations { - get; - private set; - } + public Tool[] Tools { get; private set; } + public WorkLocation[] Locations { get; private set; } public int NbWorkLocations { get { return Locations.Length; } @@ -134,26 +99,14 @@ namespace Google.OrTools.Test { get { return Tools.Length; } } - public int NbTaskPerCycle { - get; - private set; - } + public int NbTaskPerCycle { get; private set; } // TaskType go typically from 0 to 6. InspectionType indicates which // is the TaskType that correspond to Inspection. - public int Inspection { - get; - private set; - } + public int Inspection { get; private set; } // All the time within the schedule horizon in which the blast can start. - public long[] InspectionStarts { - get; - private set; - } + public long[] InspectionStarts { get; private set; } - public int Horizon { - get; - private set; - } + public int Horizon { get; private set; } // horizon equal to 2 weeks (in minutes). public FactoryDescription(int nbTools, int nbLocations, int nbTaskPerCycle, @@ -170,24 +123,22 @@ namespace Google.OrTools.Test { Locations = new WorkLocation[nbLocations]; for (int i = 0; i < nbLocations; i++) Locations[i] = new WorkLocation(i); - InspectionStarts = new long[]{-1, 600, 1200, 1800, 2400, 2800}; + InspectionStarts = new long[] { -1, 600, 1200, 1800, 2400, 2800 }; } public Tool[] getToolPerTaskType(int taskType) { - var elements = from tool in Tools where tool.CanPerformTaskType(taskType) - select tool; + var elements = from tool in Tools + where tool.CanPerformTaskType(taskType) select tool; return elements.ToArray(); } public Task[] getFlatTaskList() { - return (from location in Locations from task in - location.Tasks orderby task.Id select task) + return (from location in Locations from task in location.Tasks orderby task.Id select task) .ToArray(); } public int[] getTaskTypes() { - return (from location in Locations from task in location.Tasks select - task.TaskType) + return (from location in Locations from task in location.Tasks select task.TaskType) .Distinct() .ToArray(); } @@ -197,8 +148,7 @@ namespace Google.OrTools.Test { foreach (Tool tool in Tools) { Debug.Assert(tool.TravellingTime.GetLength(0) == NbWorkLocations); Debug.Assert(tool.TravellingTime.GetLength(1) == NbWorkLocations); - for (int i = 0; i < NbWorkLocations; i++) - Debug.Assert(tool.TravellingTime[i, i] == 0); + for (int i = 0; i < NbWorkLocations; i++) Debug.Assert(tool.TravellingTime[i, i] == 0); } } } @@ -219,8 +169,8 @@ namespace Google.OrTools.Test { // Travelling time and distance are temporarily identical and they // are no different for different tools - int[, ] travellingTime = new int[factoryDescription.NbWorkLocations, - factoryDescription.NbWorkLocations]; + int[,] travellingTime = + new int[factoryDescription.NbWorkLocations, factoryDescription.NbWorkLocations]; for (int i = 0; i < travellingTime.GetLength(0); i++) { for (int j = 0; j < travellingTime.GetLength(1); j++) { if (i == j) @@ -230,27 +180,14 @@ namespace Google.OrTools.Test { } } - factoryDescription - .Tools [0] - .AddTaskType(0); - factoryDescription - .Tools [1] - .AddTaskType(0); - factoryDescription - .Tools [2] - .AddTaskType(1); - factoryDescription - .Tools [3] - .AddTaskType(1); - factoryDescription - .Tools [4] - .AddTaskType(2); - factoryDescription - .Tools [1] - .AddTaskType(1); + factoryDescription.Tools[0].AddTaskType(0); + factoryDescription.Tools[1].AddTaskType(0); + factoryDescription.Tools[2].AddTaskType(1); + factoryDescription.Tools[3].AddTaskType(1); + factoryDescription.Tools[4].AddTaskType(2); + factoryDescription.Tools[1].AddTaskType(1); - foreach (Tool tool in factoryDescription.Tools) - tool.TravellingTime = travellingTime; + foreach (Tool tool in factoryDescription.Tools) tool.TravellingTime = travellingTime; int c = 0; int nbCyclePerWorkLocation = 2; @@ -260,8 +197,7 @@ namespace Google.OrTools.Test { nbCyclePerWorkLocation * factoryDescription.NbTaskPerCycle; for (int j = 0; j < nbCyclePerWorkLocation; j++) { for (int k = 0; k < factoryDescription.NbTaskPerCycle; k++) { - Task t = - new Task(c, k, i, k + j * factoryDescription.NbTaskPerCycle); + Task t = new Task(c, k, i, k + j * factoryDescription.NbTaskPerCycle); // Filling in tool-dependent durations Tool[] compatibleTools = factoryDescription.getToolPerTaskType(k); @@ -285,8 +221,7 @@ namespace Google.OrTools.Test { private FactoryScheduling factoryScheduling; private Random rnd; - public RandomSelectToolHeuristic(FactoryScheduling factoryScheduling, - int seed) { + public RandomSelectToolHeuristic(FactoryScheduling factoryScheduling, int seed) { this.factoryScheduling = factoryScheduling; // deterministic seed for result reproducibility this.rnd = new Random(seed); @@ -295,8 +230,8 @@ namespace Google.OrTools.Test { public override Decision Next(Solver solver) { foreach (IntVar var in factoryScheduling.SelectedTool) { if (!var.Bound()) { - int min = (int) var.Min(); - int max = (int) var.Max(); + int min = (int)var.Min(); + int max = (int)var.Max(); int rndVal = rnd.Next(min, max + 1); while (!var.Contains(rndVal)) rndVal = rnd.Next(min, max + 1); return solver.MakeAssignVariableValue(var, rndVal); @@ -307,18 +242,9 @@ namespace Google.OrTools.Test { } class TaskAlternative { - public Task Task { - get; - private set; - } - public IntVar ToolVar { - get; - set; - } - public List Intervals { - get; - private set; - } + public Task Task { get; private set; } + public IntVar ToolVar { get; set; } + public List Intervals { get; private set; } public TaskAlternative(Task t) { Task = t; @@ -385,7 +311,9 @@ namespace Google.OrTools.Test { IntVar[][] startingTimes; IntVar[][] endTimes; - public FactoryScheduling(FactoryDescription data) { factoryData = data; } + public FactoryScheduling(FactoryDescription data) { + factoryData = data; + } private void Init() { horizon = factoryData.Horizon; @@ -393,24 +321,19 @@ namespace Google.OrTools.Test { tasks = factoryData.getFlatTaskList(); taskTypes = factoryData.getTaskTypes(); taskStructures = new TaskAlternative[tasks.Length]; - location2Task = new TaskAlternative [factoryData.NbWorkLocations] - []; - tool2Task = new List[ factoryData.NbTools ]; - toolIntervalVar2TaskId = new List[ factoryData.NbTools ]; - tool2TransitionTimes = new List[ factoryData.NbTools ]; + location2Task = new TaskAlternative[factoryData.NbWorkLocations][]; + tool2Task = new List[factoryData.NbTools]; + toolIntervalVar2TaskId = new List[factoryData.NbTools]; + tool2TransitionTimes = new List[factoryData.NbTools]; - taskType2Tool = new List[ taskTypes.Length ]; + taskType2Tool = new List[taskTypes.Length]; selectedTool = new List(); - for (int tt = 0; tt < taskTypes.Length; tt++) - taskType2Tool[tt] = new List(); + for (int tt = 0; tt < taskTypes.Length; tt++) taskType2Tool[tt] = new List(); foreach (Tool tool in factoryData.Tools) - foreach (int taskType in tool.TaskTypes) - taskType2Tool [taskType] - .Add(tool); + foreach (int taskType in tool.TaskTypes) taskType2Tool[taskType].Add(tool); for (int d = 0; d < factoryData.NbWorkLocations; d++) - location2Task[d] = - new TaskAlternative[factoryData.Locations[d].NbTasks]; + location2Task[d] = new TaskAlternative[factoryData.Locations[d].NbTasks]; for (int t = 0; t < factoryData.NbTools; t++) { tool2Task[t] = new List(); toolIntervalVar2TaskId[t] = new List(); @@ -419,21 +342,17 @@ namespace Google.OrTools.Test { allToolSequences = new SequenceVar[factoryData.NbTools - 1]; - startingTimes = new IntVar [factoryData.NbTools - 1] - []; - endTimes = new IntVar [factoryData.NbTools - 1] - []; + startingTimes = new IntVar[factoryData.NbTools - 1][]; + endTimes = new IntVar[factoryData.NbTools - 1][]; } - private void PostTransitionTimeConstraints( - int t, bool postTransitionsConstraint = true) { + private void PostTransitionTimeConstraints(int t, bool postTransitionsConstraint = true) { Tool tool = factoryData.Tools[t]; // if it is a inspection, we make sure there are no transitiontimes if (tool.CanPerformTaskType(factoryData.Inspection)) - tool2TransitionTimes [t] - .Add(null); + tool2TransitionTimes[t].Add(null); else { - int[, ] tt = tool.TravellingTime; + int[,] tt = tool.TravellingTime; SequenceVar seq = allToolSequences[t]; long s = seq.Size(); @@ -458,55 +377,40 @@ namespace Google.OrTools.Test { int[] taskIndex2locationId = new int[s + 2]; taskIndex2locationId[0] = -10; for (int i = 0; i < s; i++) - taskIndex2locationId[i + 1] = tasks [toolIntervalVar2TaskId [t] - [i] - ] - .LocationId; + taskIndex2locationId[i + 1] = tasks[toolIntervalVar2TaskId[t][i]].LocationId; // this is the virtual location for unperformed tasks taskIndex2locationId[s + 1] = factoryData.NbWorkLocations; // Build the travelling time matrix with the additional virtual location - int[][] ttWithVirtualLocation = - new int [factoryData.NbWorkLocations + 1] - []; + int[][] ttWithVirtualLocation = new int [factoryData.NbWorkLocations + 1][]; for (int d1 = 0; d1 < ttWithVirtualLocation.Length; d1++) { ttWithVirtualLocation[d1] = new int[factoryData.NbWorkLocations + 1]; for (int d2 = 0; d2 < ttWithVirtualLocation.Length; d2++) if (d1 == factoryData.NbWorkLocations) { - ttWithVirtualLocation [d1] - [d2] = 0; + ttWithVirtualLocation[d1][d2] = 0; } else { - ttWithVirtualLocation [d1] - [d2] = (d2 == factoryData.NbWorkLocations) ? 0 : tt[d1, d2]; + ttWithVirtualLocation[d1][d2] = (d2 == factoryData.NbWorkLocations) ? 0 : tt[d1, d2]; } } for (int i = 0; i < nextLocation.Length; i++) { // this is the next-location associated with the i-th task - nextLocation[i] = - solver.MakeElement(taskIndex2locationId, seq.Next(i)).Var(); + nextLocation[i] = solver.MakeElement(taskIndex2locationId, seq.Next(i)).Var(); int d = (i == 0) ? tool.InitialLocationId - : tasks [toolIntervalVar2TaskId [t] - [i - 1] - ] - .LocationId; + : tasks[toolIntervalVar2TaskId[t][i - 1]].LocationId; if (i == 0) { // To be changed - right now we don't have meaningful indata // of previous location Ugly way of setting initial travel // time to = 0, as this is how we find common grounds // between benchmark algorithm and this - tool2TransitionTimes [t] - .Add(solver - .MakeElement(new int[ttWithVirtualLocation[d].Length], - nextLocation[i]) - .Var()); + tool2TransitionTimes[t].Add( + solver.MakeElement(new int[ttWithVirtualLocation[d].Length], nextLocation[i]) + .Var()); } else { - tool2TransitionTimes [t] - .Add(solver - .MakeElement(ttWithVirtualLocation[d], nextLocation[i]) - .Var()); + tool2TransitionTimes[t].Add( + solver.MakeElement(ttWithVirtualLocation[d], nextLocation[i]).Var()); } } @@ -515,41 +419,24 @@ namespace Google.OrTools.Test { startingTimes[t] = new IntVar[s + 2]; endTimes[t] = new IntVar[s + 2]; - startingTimes [t] - [0] = solver.MakeIntConst(0); + startingTimes[t][0] = solver.MakeIntConst(0); // Tbd: Set this endtime to the estimated time of finishing // previous task for the current tool - endTimes [t] - [0] = solver.MakeIntConst(0); + endTimes[t][0] = solver.MakeIntConst(0); for (int i = 0; i < s; i++) { - startingTimes [t] - [i + 1] = tool2Task [t] - [i] - .SafeStartExpr(-1) - .Var(); - endTimes [t] - [i + 1] = tool2Task [t] - [i] - .SafeEndExpr(-1) - .Var(); + startingTimes[t][i + 1] = tool2Task[t][i].SafeStartExpr(-1).Var(); + endTimes[t][i + 1] = tool2Task[t][i].SafeEndExpr(-1).Var(); } - startingTimes [t] - [s + 1] = solver.MakeIntConst(factoryData.Horizon); - endTimes [t] - [s + 1] = solver.MakeIntConst(factoryData.Horizon); + startingTimes[t][s + 1] = solver.MakeIntConst(factoryData.Horizon); + endTimes[t][s + 1] = solver.MakeIntConst(factoryData.Horizon); // Enforce (or not) that each task is separated by the // transition time to the next task for (int i = 0; i < nextLocation.Length; i++) { - IntVar nextStart = - solver.MakeElement(startingTimes[t], seq.Next(i).Var()).Var(); + IntVar nextStart = solver.MakeElement(startingTimes[t], seq.Next(i).Var()).Var(); if (postTransitionsConstraint) - solver.Add(endTimes [t] - [i] + - tool2TransitionTimes [t] - [i] <= - nextStart); + solver.Add(endTimes[t][i] + tool2TransitionTimes[t][i] <= nextStart); } } } @@ -562,8 +449,7 @@ namespace Google.OrTools.Test { taskStructures[i] = new TaskAlternative(tasks[i]); /* Container to use when posting constraints */ - location2Task[tasks[i].LocationId][tasks[i].TaskPosition] = - taskStructures[i]; + location2Task[tasks[i].LocationId][tasks[i].TaskPosition] = taskStructures[i]; /* Get task type */ int taskType = tasks[i].TaskType; @@ -587,22 +473,17 @@ namespace Google.OrTools.Test { if (taskType == factoryData.Inspection) { /* We set a 0 time if the task is an inspection */ duration = 0; - intervalVar = solver.MakeFixedDurationIntervalVar( - 0, horizon, duration, optional, name); + intervalVar = solver.MakeFixedDurationIntervalVar(0, horizon, duration, optional, name); IntVar start = intervalVar.SafeStartExpr(-1).Var(); - intervalVar.SafeStartExpr(-1).Var().SetValues( - factoryData.InspectionStarts); + intervalVar.SafeStartExpr(-1).Var().SetValues(factoryData.InspectionStarts); } else { - intervalVar = solver.MakeFixedDurationIntervalVar( - 0, horizon, duration, optional, name); + intervalVar = solver.MakeFixedDurationIntervalVar(0, horizon, duration, optional, name); } taskStructures[i].Intervals.Add(intervalVar); - tool2Task [toolId] - .Add(intervalVar); - toolIntervalVar2TaskId [toolId] - .Add(i); + tool2Task[toolId].Add(intervalVar); + toolIntervalVar2TaskId[toolId].Add(i); /* Collecting all the bool vars, even if they are optional */ performedOnTool.Add(intervalVar.PerformedExpr().Var()); @@ -611,14 +492,11 @@ namespace Google.OrTools.Test { /* Linking the bool var to a single integer variable: */ /* if alternativeToolVar == t <=> performedOnTool[t] == true */ string alternativeName = "J " + tasks[i].Id; - IntVar alternativeToolVar = - solver.MakeIntVar(0, tools.Count - 1, alternativeName); + IntVar alternativeToolVar = solver.MakeIntVar(0, tools.Count - 1, alternativeName); taskStructures[i].ToolVar = alternativeToolVar; - solver.Add(solver.MakeMapDomain(alternativeToolVar, - performedOnTool.ToArray())); - Debug.Assert(performedOnTool.ToArray().Length == - alternativeToolVar.Max() + 1); + solver.Add(solver.MakeMapDomain(alternativeToolVar, performedOnTool.ToArray())); + Debug.Assert(performedOnTool.ToArray().Length == alternativeToolVar.Max() + 1); selectedTool.Add(alternativeToolVar); } @@ -628,10 +506,8 @@ namespace Google.OrTools.Test { */ for (int d = 0; d < location2Task.Length; d++) { for (int i = 0; i < location2Task[d].Length - 1; i++) { - TaskAlternative task1 = location2Task [d] - [i]; - TaskAlternative task2 = location2Task [d] - [i + 1]; + TaskAlternative task1 = location2Task[d][i]; + TaskAlternative task2 = location2Task[d][i + 1]; /* task1 must end before task2 starts */ /* Adding precedence for each possible alternative pair */ for (int t1 = 0; t1 < task1.Intervals.Count(); t1++) { @@ -651,13 +527,8 @@ namespace Google.OrTools.Test { for (int t = 0; t < factoryData.NbTools; t++) { string name = "Tool " + t; - if (!factoryData - .Tools [t] - .CanPerformTaskType(factoryData.Inspection)) { - DisjunctiveConstraint ct = - solver.MakeDisjunctiveConstraint(tool2Task [t] - .ToArray(), - name); + if (!factoryData.Tools[t].CanPerformTaskType(factoryData.Inspection)) { + DisjunctiveConstraint ct = solver.MakeDisjunctiveConstraint(tool2Task[t].ToArray(), name); solver.Add(ct); allToolSequences[t] = ct.SequenceVar(); } @@ -679,16 +550,14 @@ namespace Google.OrTools.Test { int seed = 2; // This is a good seed to show the crash /* Assigning first tools */ - DecisionBuilder myToolAssignmentPhase = - new RandomSelectToolHeuristic(this, seed); + DecisionBuilder myToolAssignmentPhase = new RandomSelectToolHeuristic(this, seed); /* Ranking of the tools */ - DecisionBuilder sequencingPhase = - solver.MakePhase(allToolSequences, Solver.SEQUENCE_DEFAULT); + DecisionBuilder sequencingPhase = solver.MakePhase(allToolSequences, Solver.SEQUENCE_DEFAULT); /* Then fixing time of tasks as early as possible */ - DecisionBuilder timingPhase = solver.MakePhase( - makespan, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); + DecisionBuilder timingPhase = + solver.MakePhase(makespan, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE); /* Overall phase */ DecisionBuilder mainPhase = @@ -725,8 +594,7 @@ namespace Google.OrTools.Test { public class Issue18Test { [Fact] public void FactorySchedulingTest() { - FactoryScheduling scheduling = - new FactoryScheduling(new SmallSyntheticData().FetchData()); + FactoryScheduling scheduling = new FactoryScheduling(new SmallSyntheticData().FetchData()); scheduling.Solve(); } } diff --git a/ortools/algorithms/samples/Knapsack.cs b/ortools/algorithms/samples/Knapsack.cs index d7aa3b09be..711ee11988 100644 --- a/ortools/algorithms/samples/Knapsack.cs +++ b/ortools/algorithms/samples/Knapsack.cs @@ -20,25 +20,22 @@ using Google.OrTools.Algorithms; public class Knapsack { static void Main() { // [START solver] - KnapsackSolver solver = - new KnapsackSolver(KnapsackSolver.SolverType - .KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, - "KnapsackExample"); + KnapsackSolver solver = new KnapsackSolver( + KnapsackSolver.SolverType.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, + "KnapsackExample"); // [END solver] // [START data] - long[] values = {360, 83, 59, 130, 431, 67, 230, 52, 93, 125, - 670, 892, 600, 38, 48, 147, 78, 256, 63, 17, - 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, - 514, 28, 87, 73, 78, 15, 26, 78, 210, 36, - 85, 189, 274, 43, 33, 10, 19, 389, 276, 312}; + long[] values = { 360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, + 38, 48, 147, 78, 256, 63, 17, 120, 164, 432, 35, 92, 110, + 22, 42, 50, 323, 514, 28, 87, 73, 78, 15, 26, 78, 210, + 36, 85, 189, 274, 43, 33, 10, 19, 389, 276, 312 }; - long[, ] weights = {{7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, - 36, 3, 8, 15, 42, 9, 0, 42, 47, 52, 32, 26, 48, - 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71, - 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13}}; + long[,] weights = { { 7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, + 42, 9, 0, 42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, + 7, 29, 93, 44, 71, 3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13 } }; - long[] capacities = {850}; + long[] capacities = { 850 }; // [END data] // [START solve] diff --git a/ortools/base/BUILD b/ortools/base/BUILD index aaf896702b..2964ec7b96 100644 --- a/ortools/base/BUILD +++ b/ortools/base/BUILD @@ -388,9 +388,9 @@ cc_library( cc_library( name = "dynamic_library", hdrs = ["dynamic_library.h"], - deps = [":base"], linkopts = select({ "on_linux": ["-Wl,--no-as-needed -ldl"], "//conditions:default": [], }), + deps = [":base"], ) diff --git a/ortools/constraint_solver/csharp/IntVarArrayHelper.cs b/ortools/constraint_solver/csharp/IntVarArrayHelper.cs index b8d7bbd2d2..25209fb5e9 100644 --- a/ortools/constraint_solver/csharp/IntVarArrayHelper.cs +++ b/ortools/constraint_solver/csharp/IntVarArrayHelper.cs @@ -23,8 +23,7 @@ namespace Google.OrTools.ConstraintSolver { return solver.MakeAllDifferent(vars); } // Allowed assignment - public static Constraint AllowedAssignments(this IntVar[] vars, - IntTupleSet tuples) { + public static Constraint AllowedAssignments(this IntVar[] vars, IntTupleSet tuples) { Solver solver = GetSolver(vars); return solver.MakeAllowedAssignments(vars, tuples); } @@ -38,8 +37,7 @@ namespace Google.OrTools.ConstraintSolver { Solver solver = GetSolver(cts); IntVar[] vars = new IntVar[cts.Length]; for (int i = 0; i < cts.Length; ++i) { - vars[i] = cts [i] - .Var(); + vars[i] = cts[i].Var(); } return solver.MakeSum(vars); } @@ -47,8 +45,7 @@ namespace Google.OrTools.ConstraintSolver { Solver solver = GetSolver(exprs); IntVar[] vars = new IntVar[exprs.Length]; for (int i = 0; i < exprs.Length; ++i) { - vars[i] = exprs [i] - .Var(); + vars[i] = exprs[i].Var(); } return solver.MakeSum(vars); } @@ -70,23 +67,20 @@ namespace Google.OrTools.ConstraintSolver { if (vars == null || vars.Length <= 0) throw new ArgumentException("Array cannot be null or empty"); - return vars [0] - .solver(); + return vars[0].solver(); } // get solver from array of integer expressions private static Solver GetSolver(IntExpr[] expressions) { if (expressions == null || expressions.Length <= 0) throw new ArgumentException("Array cannot be null or empty"); - return expressions [0] - .solver(); + return expressions[0].solver(); } private static Solver GetSolver(IConstraintWithStatus[] cts) { if (cts == null || cts.Length <= 0) throw new ArgumentException("Array cannot be null or empty"); - return cts [0] - .solver(); + return cts[0].solver(); } public static IntExpr Element(this IntVar[] array, IntExpr index) { return index.solver().MakeElement(array, index.Var()); @@ -107,18 +101,15 @@ namespace Google.OrTools.ConstraintSolver { return solver.MakeCount(vars, value, count); } // count of all vars. - public static Constraint Count(this IntVar[] vars, long value, - IntExpr count) { + public static Constraint Count(this IntVar[] vars, long value, IntExpr count) { Solver solver = GetSolver(vars); return solver.MakeCount(vars, value, count.Var()); } - public static Constraint Distribute(this IntVar[] vars, long[] values, - IntVar[] cards) { + public static Constraint Distribute(this IntVar[] vars, long[] values, IntVar[] cards) { Solver solver = GetSolver(vars); return solver.MakeDistribute(vars, values, cards); } - public static Constraint Distribute(this IntVar[] vars, int[] values, - IntVar[] cards) { + public static Constraint Distribute(this IntVar[] vars, int[] values, IntVar[] cards) { Solver solver = GetSolver(vars); return solver.MakeDistribute(vars, values, cards); } @@ -126,30 +117,24 @@ namespace Google.OrTools.ConstraintSolver { Solver solver = GetSolver(vars); return solver.MakeDistribute(vars, cards); } - public static Constraint Distribute(this IntVar[] vars, long card_min, - long card_max, long card_size) { + public static Constraint Distribute(this IntVar[] vars, long card_min, long card_max, + long card_size) { Solver solver = GetSolver(vars); return solver.MakeDistribute(vars, card_min, card_max, card_size); } - public static Constraint Transition(this IntVar[] vars, - IntTupleSet transitions, - long initial_state, - long[] final_states) { + public static Constraint Transition(this IntVar[] vars, IntTupleSet transitions, + long initial_state, long[] final_states) { Solver solver = GetSolver(vars); - return solver.MakeTransitionConstraint(vars, transitions, initial_state, - final_states); + return solver.MakeTransitionConstraint(vars, transitions, initial_state, final_states); } - public static Constraint Transition(this IntVar[] vars, - IntTupleSet transitions, - long initial_state, - int[] final_states) { + public static Constraint Transition(this IntVar[] vars, IntTupleSet transitions, + long initial_state, int[] final_states) { Solver solver = GetSolver(vars); - return solver.MakeTransitionConstraint(vars, transitions, initial_state, - final_states); + return solver.MakeTransitionConstraint(vars, transitions, initial_state, final_states); } // Matrix API - public static IntVar[] Flatten(this IntVar[, ] vars) { + public static IntVar[] Flatten(this IntVar[,] vars) { int rows = vars.GetLength(0); int cols = vars.GetLength(1); IntVar[] flat = new IntVar[cols * rows]; @@ -187,12 +172,11 @@ namespace Google.OrTools.ConstraintSolver { } } - public partial class SearchMonitorVector - : IDisposable, - System.Collections.IEnumerable + public partial class SearchMonitorVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# SearchMonitor array @@ -212,17 +196,15 @@ namespace Google.OrTools.ConstraintSolver { } } - public partial class DecisionBuilderVector - : IDisposable, - System.Collections.IEnumerable + public partial class DecisionBuilderVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# DecisionBuilder array - public static implicit operator DecisionBuilderVector( - DecisionBuilder[] inVal) { + public static implicit operator DecisionBuilderVector(DecisionBuilder[] inVal) { var outVal = new DecisionBuilderVector(); foreach (DecisionBuilder element in inVal) { outVal.Add(element); @@ -231,20 +213,18 @@ namespace Google.OrTools.ConstraintSolver { } // cast to C# DecisionBuilder array - public static implicit operator DecisionBuilder[]( - DecisionBuilderVector inVal) { + public static implicit operator DecisionBuilder[](DecisionBuilderVector inVal) { var outVal = new DecisionBuilder[inVal.Count]; inVal.CopyTo(outVal); return outVal; } } - public partial class IntervalVarVector - : IDisposable, - System.Collections.IEnumerable + public partial class IntervalVarVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# IntervalVar array @@ -264,12 +244,11 @@ namespace Google.OrTools.ConstraintSolver { } } - public partial class SequenceVarVector - : IDisposable, - System.Collections.IEnumerable + public partial class SequenceVarVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# SequenceVar array @@ -298,8 +277,7 @@ namespace Google.OrTools.ConstraintSolver { #endif { // cast from C# LocalSearchOperator array - public static implicit operator LocalSearchOperatorVector( - LocalSearchOperator[] inVal) { + public static implicit operator LocalSearchOperatorVector(LocalSearchOperator[] inVal) { var outVal = new LocalSearchOperatorVector(); foreach (LocalSearchOperator element in inVal) { outVal.Add(element); @@ -308,25 +286,22 @@ namespace Google.OrTools.ConstraintSolver { } // cast to C# LocalSearchOperator array - public static implicit operator LocalSearchOperator[]( - LocalSearchOperatorVector inVal) { + public static implicit operator LocalSearchOperator[](LocalSearchOperatorVector inVal) { var outVal = new LocalSearchOperator[inVal.Count]; inVal.CopyTo(outVal); return outVal; } } - public partial class LocalSearchFilterVector - : IDisposable, - System.Collections.IEnumerable + public partial class LocalSearchFilterVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# LocalSearchFilter array - public static implicit operator LocalSearchFilterVector( - LocalSearchFilter[] inVal) { + public static implicit operator LocalSearchFilterVector(LocalSearchFilter[] inVal) { var outVal = new LocalSearchFilterVector(); foreach (LocalSearchFilter element in inVal) { outVal.Add(element); @@ -335,25 +310,22 @@ namespace Google.OrTools.ConstraintSolver { } // cast to C# LocalSearchFilter array - public static implicit operator LocalSearchFilter[]( - LocalSearchFilterVector inVal) { + public static implicit operator LocalSearchFilter[](LocalSearchFilterVector inVal) { var outVal = new LocalSearchFilter[inVal.Count]; inVal.CopyTo(outVal); return outVal; } } - public partial class SymmetryBreakerVector - : IDisposable, - System.Collections.IEnumerable + public partial class SymmetryBreakerVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# SymmetryBreaker array - public static implicit operator SymmetryBreakerVector( - SymmetryBreaker[] inVal) { + public static implicit operator SymmetryBreakerVector(SymmetryBreaker[] inVal) { var outVal = new SymmetryBreakerVector(); foreach (SymmetryBreaker element in inVal) { outVal.Add(element); @@ -362,8 +334,7 @@ namespace Google.OrTools.ConstraintSolver { } // cast to C# SymmetryBreaker array - public static implicit operator SymmetryBreaker[]( - SymmetryBreakerVector inVal) { + public static implicit operator SymmetryBreaker[](SymmetryBreakerVector inVal) { var outVal = new SymmetryBreaker[inVal.Count]; inVal.CopyTo(outVal); return outVal; diff --git a/ortools/constraint_solver/csharp/IntervalVarArrayHelper.cs b/ortools/constraint_solver/csharp/IntervalVarArrayHelper.cs index faf903fcf4..d77609309e 100644 --- a/ortools/constraint_solver/csharp/IntervalVarArrayHelper.cs +++ b/ortools/constraint_solver/csharp/IntervalVarArrayHelper.cs @@ -22,21 +22,19 @@ namespace Google.OrTools.ConstraintSolver { if (vars == null || vars.Length <= 0) throw new ArgumentException("Array cannot be null or empty"); - return vars [0] - .solver(); + return vars[0].solver(); } - public static DisjunctiveConstraint Disjunctive(this IntervalVar[] vars, - String name) { + public static DisjunctiveConstraint Disjunctive(this IntervalVar[] vars, String name) { Solver solver = GetSolver(vars); return solver.MakeDisjunctiveConstraint(vars, name); } - public static Constraint Cumulative(this IntervalVar[] vars, long[] demands, - long capacity, String name) { + public static Constraint Cumulative(this IntervalVar[] vars, long[] demands, long capacity, + String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } - public static Constraint Cumulative(this IntervalVar[] vars, int[] demands, - long capacity, String name) { + public static Constraint Cumulative(this IntervalVar[] vars, int[] demands, long capacity, + String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } diff --git a/ortools/constraint_solver/csharp/NetDecisionBuilder.cs b/ortools/constraint_solver/csharp/NetDecisionBuilder.cs index aff34795f1..73b829cb18 100644 --- a/ortools/constraint_solver/csharp/NetDecisionBuilder.cs +++ b/ortools/constraint_solver/csharp/NetDecisionBuilder.cs @@ -39,7 +39,9 @@ namespace Google.OrTools.ConstraintSolver { /** * This is the new method to subclass when defining a .Net decision builder. */ - public virtual Decision Next(Solver solver) { return null; } + public virtual Decision Next(Solver solver) { + return null; + } } /** @@ -101,8 +103,12 @@ namespace Google.OrTools.ConstraintSolver { * This is the new method to subclass when defining a .Net decision builder. */ public virtual void Run(Solver solver) {} - public override int Priority() { return Solver.NORMAL_PRIORITY; } - public override string ToString() { return "NetDemon"; } + public override int Priority() { + return Solver.NORMAL_PRIORITY; + } + public override string ToString() { + return "NetDemon"; + } } public class NetConstraint : Constraint { @@ -116,7 +122,9 @@ namespace Google.OrTools.ConstraintSolver { } } public virtual void InitialPropagate() {} - public override string ToString() { return "NetConstraint"; } + public override string ToString() { + return "NetConstraint"; + } } public class IntVarEnumerator : IEnumerator { @@ -126,7 +134,9 @@ namespace Google.OrTools.ConstraintSolver { // until the first MoveNext() call. private bool first_ = true; - public IntVarEnumerator(IntVarIterator iterator) { iterator_ = iterator; } + public IntVarEnumerator(IntVarIterator iterator) { + iterator_ = iterator; + } public bool MoveNext() { if (first_) { @@ -138,7 +148,9 @@ namespace Google.OrTools.ConstraintSolver { return iterator_.Ok(); } - public void Reset() { first_ = true; } + public void Reset() { + first_ = true; + } object IEnumerator.Current { get { return Current; } @@ -157,7 +169,7 @@ namespace Google.OrTools.ConstraintSolver { public partial class IntVarIterator : BaseObject, IEnumerable { IEnumerator IEnumerable.GetEnumerator() { - return (IEnumerator) GetEnumerator(); + return (IEnumerator)GetEnumerator(); } public IntVarEnumerator GetEnumerator() { diff --git a/ortools/constraint_solver/csharp/SolverHelper.cs b/ortools/constraint_solver/csharp/SolverHelper.cs index 30eeeaf9d9..020536938a 100644 --- a/ortools/constraint_solver/csharp/SolverHelper.cs +++ b/ortools/constraint_solver/csharp/SolverHelper.cs @@ -19,19 +19,16 @@ namespace Google.OrTools.ConstraintSolver { public IntVar[] MakeIntVarArray(int count, long min, long max) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeIntVar(min, max); + array[i] = MakeIntVar(min, max); } return array; } - public IntVar[] MakeIntVarArray(int count, long min, long max, - string name) { + public IntVar[] MakeIntVarArray(int count, long min, long max, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; - array [i] - = MakeIntVar(min, max, var_name); + array[i] = MakeIntVar(min, max, var_name); } return array; } @@ -39,8 +36,7 @@ namespace Google.OrTools.ConstraintSolver { public IntVar[] MakeIntVarArray(int count, long[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeIntVar(values); + array[i] = MakeIntVar(values); } return array; } @@ -49,8 +45,7 @@ namespace Google.OrTools.ConstraintSolver { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; - array [i] - = MakeIntVar(values, var_name); + array[i] = MakeIntVar(values, var_name); } return array; } @@ -58,8 +53,7 @@ namespace Google.OrTools.ConstraintSolver { public IntVar[] MakeIntVarArray(int count, int[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeIntVar(values); + array[i] = MakeIntVar(values); } return array; } @@ -68,8 +62,7 @@ namespace Google.OrTools.ConstraintSolver { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; - array [i] - = MakeIntVar(values, var_name); + array[i] = MakeIntVar(values, var_name); } return array; } @@ -77,8 +70,7 @@ namespace Google.OrTools.ConstraintSolver { public IntVar[] MakeBoolVarArray(int count) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeBoolVar(); + array[i] = MakeBoolVar(); } return array; } @@ -87,175 +79,151 @@ namespace Google.OrTools.ConstraintSolver { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; - array [i] - = MakeBoolVar(var_name); + array[i] = MakeBoolVar(var_name); } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, long min, long max) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - array [i, j] - = MakeIntVar(min, max); + array[i, j] = MakeIntVar(min, max); } } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, long min, long max, - string name) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max, string name) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - array [i, j] - = MakeIntVar(min, max, var_name); + array[i, j] = MakeIntVar(min, max, var_name); } } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, long[] values) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - array [i, j] - = MakeIntVar(values); + array[i, j] = MakeIntVar(values); } } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, long[] values, - string name) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values, string name) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - array [i, j] - = MakeIntVar(values, var_name); + array[i, j] = MakeIntVar(values, var_name); } } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, int[] values) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - array [i, j] - = MakeIntVar(values); + array[i, j] = MakeIntVar(values); } } return array; } - public IntVar[, ] MakeIntVarMatrix(int rows, int cols, int[] values, - string name) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values, string name) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - array [i, j] - = MakeIntVar(values, var_name); + array[i, j] = MakeIntVar(values, var_name); } } return array; } - public IntVar[, ] MakeBoolVarMatrix(int rows, int cols) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeBoolVarMatrix(int rows, int cols) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - array [i, j] - = MakeBoolVar(); + array[i, j] = MakeBoolVar(); } } return array; } - public IntVar[, ] MakeBoolVarMatrix(int rows, int cols, string name) { - IntVar[, ] array = new IntVar[rows, cols]; + public IntVar[,] MakeBoolVarMatrix(int rows, int cols, string name) { + IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - array [i, j] - = MakeBoolVar(var_name); + array[i, j] = MakeBoolVar(var_name); } } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, - long start_min, - long start_max, - long duration, + public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, + long start_max, long duration, bool optional) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, - ""); + array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, ""); } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray( - int count, long start_min, long start_max, long duration, bool optional, - string name) { + public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, + long start_max, long duration, + bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, - name + i); + array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, name + i); } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray( - int count, long[] start_min, long[] start_max, long[] duration, - bool optional, string name) { + public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long[] start_min, + long[] start_max, long[] duration, + bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], - optional, name + i); + array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, + name + i); } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray( - int count, int[] start_min, int[] start_max, int[] duration, - bool optional, string name) { + public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, int[] start_min, + int[] start_max, int[] duration, + bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], - optional, name + i); + array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, + name + i); } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, - int[] durations, + public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, int[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); + array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } - public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, - long[] durations, + public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, long[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); + array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } @@ -272,8 +240,7 @@ namespace Google.OrTools.ConstraintSolver { NewSearchAux(db, sm1); } - public void NewSearch(DecisionBuilder db, SearchMonitor sm1, - SearchMonitor sm2) { + public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); @@ -281,8 +248,8 @@ namespace Google.OrTools.ConstraintSolver { NewSearchAux(db, sm1, sm2); } - public void NewSearch(DecisionBuilder db, SearchMonitor sm1, - SearchMonitor sm2, SearchMonitor sm3) { + public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, + SearchMonitor sm3) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); @@ -291,9 +258,8 @@ namespace Google.OrTools.ConstraintSolver { NewSearchAux(db, sm1, sm2, sm3); } - public void NewSearch(DecisionBuilder db, SearchMonitor sm1, - SearchMonitor sm2, SearchMonitor sm3, - SearchMonitor sm4) { + public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, + SearchMonitor sm3, SearchMonitor sm4) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); @@ -316,8 +282,7 @@ namespace Google.OrTools.ConstraintSolver { EndSearchAux(); } - private System.Collections.Generic - .List pinned_search_monitors_ = + private System.Collections.Generic.List pinned_search_monitors_ = new System.Collections.Generic.List(); private DecisionBuilder pinned_decision_builder_; } @@ -359,8 +324,12 @@ namespace Google.OrTools.ConstraintSolver { public static IntExpr operator -(IntExpr a) { return a.solver().MakeOpposite(a); } - public IntExpr Abs() { return this.solver().MakeAbs(this); } - public IntExpr Square() { return this.solver().MakeSquare(this); } + public IntExpr Abs() { + return this.solver().MakeAbs(this); + } + public IntExpr Square() { + return this.solver().MakeSquare(this); + } public static IntExprEquality operator ==(IntExpr a, IntExpr b) { return new IntExprEquality(a, b, true); } @@ -386,26 +355,27 @@ namespace Google.OrTools.ConstraintSolver { return new WrappedConstraint(a.solver().MakeLess(a, v)); } public static WrappedConstraint operator >=(IntExpr a, IntExpr b) { - return new WrappedConstraint( - a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); + return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(IntExpr a, IntExpr b) { - return new WrappedConstraint( - a.solver().MakeLessOrEqual(a.Var(), b.Var())); + return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } } - public partial class Constraint : PropagationBaseObject, - IConstraintWithStatus { - public static implicit operator IntVar(Constraint eq) { return eq.Var(); } + public partial class Constraint : PropagationBaseObject, IConstraintWithStatus { + public static implicit operator IntVar(Constraint eq) { + return eq.Var(); + } - public static implicit operator IntExpr(Constraint eq) { return eq.Var(); } + public static implicit operator IntExpr(Constraint eq) { + return eq.Var(); + } public static IntExpr operator +(Constraint a, Constraint b) { return a.solver().MakeSum(a.Var(), b.Var()); } @@ -439,8 +409,12 @@ namespace Google.OrTools.ConstraintSolver { public static IntExpr operator -(Constraint a) { return a.solver().MakeOpposite(a.Var()); } - public IntExpr Abs() { return this.solver().MakeAbs(this.Var()); } - public IntExpr Square() { return this.solver().MakeSquare(this.Var()); } + public IntExpr Abs() { + return this.solver().MakeAbs(this.Var()); + } + public IntExpr Square() { + return this.solver().MakeSquare(this.Var()); + } public static WrappedConstraint operator ==(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } @@ -478,15 +452,13 @@ namespace Google.OrTools.ConstraintSolver { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator >=(Constraint a, Constraint b) { - return new WrappedConstraint( - a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); + return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(Constraint a, Constraint b) { - return new WrappedConstraint( - a.solver().MakeLessOrEqual(a.Var(), b.Var())); + return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); diff --git a/ortools/constraint_solver/csharp/ValCstPair.cs b/ortools/constraint_solver/csharp/ValCstPair.cs index 3497902106..472abb5e59 100644 --- a/ortools/constraint_solver/csharp/ValCstPair.cs +++ b/ortools/constraint_solver/csharp/ValCstPair.cs @@ -57,8 +57,12 @@ namespace Google.OrTools.ConstraintSolver { public static IntExpr operator -(BaseEquality a) { return a.solver().MakeOpposite(a.Var()); } - public IntExpr Abs() { return this.solver().MakeAbs(this.Var()); } - public IntExpr Square() { return this.solver().MakeSquare(this.Var()); } + public IntExpr Abs() { + return this.solver().MakeAbs(this.Var()); + } + public IntExpr Square() { + return this.solver().MakeSquare(this.Var()); + } public static WrappedConstraint operator ==(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } @@ -95,42 +99,30 @@ namespace Google.OrTools.ConstraintSolver { public static WrappedConstraint operator<(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } - public static WrappedConstraint operator >=(BaseEquality a, - BaseEquality b) { - return new WrappedConstraint( - a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); + public static WrappedConstraint operator >=(BaseEquality a, BaseEquality b) { + return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } - public static WrappedConstraint operator <=(BaseEquality a, - BaseEquality b) { - return new WrappedConstraint( - a.solver().MakeLessOrEqual(a.Var(), b.Var())); + public static WrappedConstraint operator <=(BaseEquality a, BaseEquality b) { + return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } - public static ConstraintEquality operator ==(BaseEquality a, - BaseEquality b) { + public static ConstraintEquality operator ==(BaseEquality a, BaseEquality b) { return new ConstraintEquality(a, b, true); } - public static ConstraintEquality operator !=(BaseEquality a, - BaseEquality b) { + public static ConstraintEquality operator !=(BaseEquality a, BaseEquality b) { return new ConstraintEquality(a, b, false); } } public class WrappedConstraint : BaseEquality { - public bool Val { - get; - set; - } + public bool Val { get; set; } - public Constraint Cst { - get; - set; - } + public Constraint Cst { get; set; } public WrappedConstraint(Constraint cst) : this(true, cst) {} @@ -157,9 +149,13 @@ namespace Google.OrTools.ConstraintSolver { return eq.Var(); } - public override Solver solver() { return this.Cst.solver(); } + public override Solver solver() { + return this.Cst.solver(); + } - public override IntVar Var() { return Cst.Var(); } + public override IntVar Var() { + return Cst.Var(); + } } public class IntExprEquality : BaseEquality { @@ -170,17 +166,17 @@ namespace Google.OrTools.ConstraintSolver { } bool IsTrue() { - return (object) left_ == (object) right_ ? equality_ : !equality_; + return (object)left_ == (object)right_ ? equality_ : !equality_; } Constraint ToConstraint() { - return equality_ ? left_.solver() - .MakeEquality(left_.Var(), right_.Var()) - : left_.solver() - .MakeNonEquality(left_.Var(), right_.Var()); + return equality_ ? left_.solver().MakeEquality(left_.Var(), right_.Var()) + : left_.solver().MakeNonEquality(left_.Var(), right_.Var()); } - public static bool operator true(IntExprEquality eq) { return eq.IsTrue(); } + public static bool operator true(IntExprEquality eq) { + return eq.IsTrue(); + } public static bool operator false(IntExprEquality eq) { return !eq.IsTrue(); @@ -192,7 +188,7 @@ namespace Google.OrTools.ConstraintSolver { public override IntVar Var() { return equality_ ? left_.solver().MakeIsEqualVar(left_, right_) - : left_.solver().MakeIsDifferentVar(left_, right_); + : left_.solver().MakeIsDifferentVar(left_, right_); } public static implicit operator IntVar(IntExprEquality eq) { @@ -203,7 +199,9 @@ namespace Google.OrTools.ConstraintSolver { return eq.Var(); } - public override Solver solver() { return left_.solver(); } + public override Solver solver() { + return left_.solver(); + } private IntExpr left_; private IntExpr right_; @@ -211,22 +209,19 @@ namespace Google.OrTools.ConstraintSolver { } public class ConstraintEquality : BaseEquality { - public ConstraintEquality(IConstraintWithStatus a, IConstraintWithStatus b, - bool equality) { + public ConstraintEquality(IConstraintWithStatus a, IConstraintWithStatus b, bool equality) { this.left_ = a; this.right_ = b; this.equality_ = equality; } bool IsTrue() { - return (object) left_ == (object) right_ ? equality_ : !equality_; + return (object)left_ == (object)right_ ? equality_ : !equality_; } Constraint ToConstraint() { - return equality_ ? left_.solver() - .MakeEquality(left_.Var(), right_.Var()) - : left_.solver() - .MakeNonEquality(left_.Var(), right_.Var()); + return equality_ ? left_.solver().MakeEquality(left_.Var(), right_.Var()) + : left_.solver().MakeNonEquality(left_.Var(), right_.Var()); } public static bool operator true(ConstraintEquality eq) { @@ -242,10 +237,8 @@ namespace Google.OrTools.ConstraintSolver { } public override IntVar Var() { - return equality_ ? left_.solver() - .MakeIsEqualVar(left_.Var(), right_.Var()) - : left_.solver() - .MakeIsDifferentVar(left_.Var(), right_.Var()); + return equality_ ? left_.solver().MakeIsEqualVar(left_.Var(), right_.Var()) + : left_.solver().MakeIsDifferentVar(left_.Var(), right_.Var()); } public static implicit operator IntVar(ConstraintEquality eq) { @@ -256,7 +249,9 @@ namespace Google.OrTools.ConstraintSolver { return eq.Var(); } - public override Solver solver() { return left_.solver(); } + public override Solver solver() { + return left_.solver(); + } private IConstraintWithStatus left_; private IConstraintWithStatus right_; diff --git a/ortools/constraint_solver/samples/SimpleCpProgram.cs b/ortools/constraint_solver/samples/SimpleCpProgram.cs index c6dc5812a0..1089059a7e 100644 --- a/ortools/constraint_solver/samples/SimpleCpProgram.cs +++ b/ortools/constraint_solver/samples/SimpleCpProgram.cs @@ -37,15 +37,14 @@ public class SimpleCpProgram { // Constraint 0: x != y.. // [START constraints] - solver.Add(solver.MakeAllDifferent(new IntVar[]{x, y})); + solver.Add(solver.MakeAllDifferent(new IntVar[] { x, y })); Console.WriteLine($"Number of constraints: {solver.Constraints()}"); // [END constraints] // Solve the problem. // [START solve] - DecisionBuilder db = - solver.MakePhase(new IntVar[]{x, y, z}, Solver.CHOOSE_FIRST_UNBOUND, - Solver.ASSIGN_MIN_VALUE); + DecisionBuilder db = solver.MakePhase(new IntVar[] { x, y, z }, Solver.CHOOSE_FIRST_UNBOUND, + Solver.ASSIGN_MIN_VALUE); // [END solve] // Print solution on console. @@ -54,8 +53,7 @@ public class SimpleCpProgram { solver.NewSearch(db); while (solver.NextSolution()) { ++count; - Console.WriteLine( - $"Solution: {count}\n x={x.Value()} y={y.Value()} z={z.Value()}"); + Console.WriteLine($"Solution: {count}\n x={x.Value()} y={y.Value()} z={z.Value()}"); } solver.EndSearch(); Console.WriteLine($"Number of solutions found: {solver.Solutions()}"); diff --git a/ortools/constraint_solver/samples/SimpleRoutingProgram.cs b/ortools/constraint_solver/samples/SimpleRoutingProgram.cs index 2ace3be674..5638966db4 100644 --- a/ortools/constraint_solver/samples/SimpleRoutingProgram.cs +++ b/ortools/constraint_solver/samples/SimpleRoutingProgram.cs @@ -31,8 +31,7 @@ public class SimpleRoutingProgram { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = - new RoutingIndexManager(numLocation, numVehicles, depot); + RoutingIndexManager manager = new RoutingIndexManager(numLocation, numVehicles, depot); // [END index_manager] // Create Routing Model. @@ -42,13 +41,12 @@ public class SimpleRoutingProgram { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return Math.Abs(toNode - fromNode); - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return Math.Abs(toNode - fromNode); + }); // [END transit_callback] // Define cost of each arc. @@ -60,8 +58,7 @@ public class SimpleRoutingProgram { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. @@ -77,7 +74,7 @@ public class SimpleRoutingProgram { Console.WriteLine("Route for Vehicle 0:"); long route_distance = 0; while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); long previousIndex = index; index = solution.Value(routing.NextVar(index)); route_distance += routing.GetArcCostForVehicle(previousIndex, index, 0); diff --git a/ortools/constraint_solver/samples/Tsp.cs b/ortools/constraint_solver/samples/Tsp.cs index 5e78c1c368..98c4364dfd 100644 --- a/ortools/constraint_solver/samples/Tsp.cs +++ b/ortools/constraint_solver/samples/Tsp.cs @@ -34,9 +34,9 @@ public class Tsp { Locations[i, 1] *= 80; } } - public int[, ] Locations = {{4, 4}, {2, 0}, {8, 0}, {0, 1}, {1, 1}, {5, 2}, - {7, 2}, {3, 3}, {6, 3}, {5, 5}, {8, 5}, {1, 6}, - {2, 6}, {3, 7}, {6, 7}, {0, 8}, {7, 8}}; + public int[,] Locations = { { 4, 4 }, { 2, 0 }, { 8, 0 }, { 0, 1 }, { 1, 1 }, { 5, 2 }, + { 7, 2 }, { 3, 3 }, { 6, 3 }, { 5, 5 }, { 8, 5 }, { 1, 6 }, + { 2, 6 }, { 3, 7 }, { 6, 7 }, { 0, 8 }, { 7, 8 } }; public int VehicleNumber = 1; public int Depot = 0; }; @@ -49,8 +49,7 @@ public class Tsp { /// positions of two different indices. /// class ManhattanDistance { - public ManhattanDistance(in DataModel data, - in RoutingIndexManager manager) { + public ManhattanDistance(in DataModel data, in RoutingIndexManager manager) { // precompute distance between location to have distance callback in O(1) int locationNumber = data.Locations.GetLength(0); distancesMatrix_ = new long[locationNumber, locationNumber]; @@ -61,10 +60,8 @@ public class Tsp { distancesMatrix_[fromNode, toNode] = 0; else distancesMatrix_[fromNode, toNode] = - Math.Abs(data.Locations[toNode, 0] - - data.Locations[fromNode, 0]) + - Math.Abs(data.Locations[toNode, 1] - - data.Locations[fromNode, 1]); + Math.Abs(data.Locations[toNode, 0] - data.Locations[fromNode, 0]) + + Math.Abs(data.Locations[toNode, 1] - data.Locations[fromNode, 1]); } } } @@ -78,7 +75,7 @@ public class Tsp { int toNode = indexManager_.IndexToNode(toIndex); return distancesMatrix_[fromNode, toNode]; } - private long[, ] distancesMatrix_; + private long[,] distancesMatrix_; private RoutingIndexManager indexManager_; }; // [END manhattan_distance] @@ -87,8 +84,7 @@ public class Tsp { /// /// Print the solution. /// - static void PrintSolution(in RoutingModel routing, - in RoutingIndexManager manager, + static void PrintSolution(in RoutingModel routing, in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine("Objective: {0}", solution.ObjectiveValue()); // Inspect solution. @@ -96,12 +92,12 @@ public class Tsp { long routeDistance = 0; var index = routing.Start(0); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); } // [END solution_printer] @@ -114,8 +110,8 @@ public class Tsp { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.Locations.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.Locations.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -126,8 +122,7 @@ public class Tsp { // Create and register a transit callback. // [START transit_callback] var distanceCallback = new ManhattanDistance(data, manager); - int transitCallbackIndex = - routing.RegisterTransitCallback(distanceCallback.Call); + int transitCallbackIndex = routing.RegisterTransitCallback(distanceCallback.Call); // [END transit_callback] // Define cost of each arc. @@ -139,8 +134,7 @@ public class Tsp { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/TspCircuitBoard.cs b/ortools/constraint_solver/samples/TspCircuitBoard.cs index f45db0071c..a9eaa9b7cf 100644 --- a/ortools/constraint_solver/samples/TspCircuitBoard.cs +++ b/ortools/constraint_solver/samples/TspCircuitBoard.cs @@ -26,54 +26,54 @@ using Google.OrTools.ConstraintSolver; public class TspCircuitBoard { // [START data_model] class DataModel { - public int[, ] Locations = { - {288, 149}, {288, 129}, {270, 133}, {256, 141}, {256, 157}, {246, 157}, - {236, 169}, {228, 169}, {228, 161}, {220, 169}, {212, 169}, {204, 169}, - {196, 169}, {188, 169}, {196, 161}, {188, 145}, {172, 145}, {164, 145}, - {156, 145}, {148, 145}, {140, 145}, {148, 169}, {164, 169}, {172, 169}, - {156, 169}, {140, 169}, {132, 169}, {124, 169}, {116, 161}, {104, 153}, - {104, 161}, {104, 169}, {90, 165}, {80, 157}, {64, 157}, {64, 165}, - {56, 169}, {56, 161}, {56, 153}, {56, 145}, {56, 137}, {56, 129}, - {56, 121}, {40, 121}, {40, 129}, {40, 137}, {40, 145}, {40, 153}, - {40, 161}, {40, 169}, {32, 169}, {32, 161}, {32, 153}, {32, 145}, - {32, 137}, {32, 129}, {32, 121}, {32, 113}, {40, 113}, {56, 113}, - {56, 105}, {48, 99}, {40, 99}, {32, 97}, {32, 89}, {24, 89}, - {16, 97}, {16, 109}, {8, 109}, {8, 97}, {8, 89}, {8, 81}, - {8, 73}, {8, 65}, {8, 57}, {16, 57}, {8, 49}, {8, 41}, - {24, 45}, {32, 41}, {32, 49}, {32, 57}, {32, 65}, {32, 73}, - {32, 81}, {40, 83}, {40, 73}, {40, 63}, {40, 51}, {44, 43}, - {44, 35}, {44, 27}, {32, 25}, {24, 25}, {16, 25}, {16, 17}, - {24, 17}, {32, 17}, {44, 11}, {56, 9}, {56, 17}, {56, 25}, - {56, 33}, {56, 41}, {64, 41}, {72, 41}, {72, 49}, {56, 49}, - {48, 51}, {56, 57}, {56, 65}, {48, 63}, {48, 73}, {56, 73}, - {56, 81}, {48, 83}, {56, 89}, {56, 97}, {104, 97}, {104, 105}, - {104, 113}, {104, 121}, {104, 129}, {104, 137}, {104, 145}, {116, 145}, - {124, 145}, {132, 145}, {132, 137}, {140, 137}, {148, 137}, {156, 137}, - {164, 137}, {172, 125}, {172, 117}, {172, 109}, {172, 101}, {172, 93}, - {172, 85}, {180, 85}, {180, 77}, {180, 69}, {180, 61}, {180, 53}, - {172, 53}, {172, 61}, {172, 69}, {172, 77}, {164, 81}, {148, 85}, - {124, 85}, {124, 93}, {124, 109}, {124, 125}, {124, 117}, {124, 101}, - {104, 89}, {104, 81}, {104, 73}, {104, 65}, {104, 49}, {104, 41}, - {104, 33}, {104, 25}, {104, 17}, {92, 9}, {80, 9}, {72, 9}, - {64, 21}, {72, 25}, {80, 25}, {80, 25}, {80, 41}, {88, 49}, - {104, 57}, {124, 69}, {124, 77}, {132, 81}, {140, 65}, {132, 61}, - {124, 61}, {124, 53}, {124, 45}, {124, 37}, {124, 29}, {132, 21}, - {124, 21}, {120, 9}, {128, 9}, {136, 9}, {148, 9}, {162, 9}, - {156, 25}, {172, 21}, {180, 21}, {180, 29}, {172, 29}, {172, 37}, - {172, 45}, {180, 45}, {180, 37}, {188, 41}, {196, 49}, {204, 57}, - {212, 65}, {220, 73}, {228, 69}, {228, 77}, {236, 77}, {236, 69}, - {236, 61}, {228, 61}, {228, 53}, {236, 53}, {236, 45}, {228, 45}, - {228, 37}, {236, 37}, {236, 29}, {228, 29}, {228, 21}, {236, 21}, - {252, 21}, {260, 29}, {260, 37}, {260, 45}, {260, 53}, {260, 61}, - {260, 69}, {260, 77}, {276, 77}, {276, 69}, {276, 61}, {276, 53}, - {284, 53}, {284, 61}, {284, 69}, {284, 77}, {284, 85}, {284, 93}, - {284, 101}, {288, 109}, {280, 109}, {276, 101}, {276, 93}, {276, 85}, - {268, 97}, {260, 109}, {252, 101}, {260, 93}, {260, 85}, {236, 85}, - {228, 85}, {228, 93}, {236, 93}, {236, 101}, {228, 101}, {228, 109}, - {228, 117}, {228, 125}, {220, 125}, {212, 117}, {204, 109}, {196, 101}, - {188, 93}, {180, 93}, {180, 101}, {180, 109}, {180, 117}, {180, 125}, - {196, 145}, {204, 145}, {212, 145}, {220, 145}, {228, 145}, {236, 145}, - {246, 141}, {252, 125}, {260, 129}, {280, 133}, + public int[,] Locations = { + { 288, 149 }, { 288, 129 }, { 270, 133 }, { 256, 141 }, { 256, 157 }, { 246, 157 }, + { 236, 169 }, { 228, 169 }, { 228, 161 }, { 220, 169 }, { 212, 169 }, { 204, 169 }, + { 196, 169 }, { 188, 169 }, { 196, 161 }, { 188, 145 }, { 172, 145 }, { 164, 145 }, + { 156, 145 }, { 148, 145 }, { 140, 145 }, { 148, 169 }, { 164, 169 }, { 172, 169 }, + { 156, 169 }, { 140, 169 }, { 132, 169 }, { 124, 169 }, { 116, 161 }, { 104, 153 }, + { 104, 161 }, { 104, 169 }, { 90, 165 }, { 80, 157 }, { 64, 157 }, { 64, 165 }, + { 56, 169 }, { 56, 161 }, { 56, 153 }, { 56, 145 }, { 56, 137 }, { 56, 129 }, + { 56, 121 }, { 40, 121 }, { 40, 129 }, { 40, 137 }, { 40, 145 }, { 40, 153 }, + { 40, 161 }, { 40, 169 }, { 32, 169 }, { 32, 161 }, { 32, 153 }, { 32, 145 }, + { 32, 137 }, { 32, 129 }, { 32, 121 }, { 32, 113 }, { 40, 113 }, { 56, 113 }, + { 56, 105 }, { 48, 99 }, { 40, 99 }, { 32, 97 }, { 32, 89 }, { 24, 89 }, + { 16, 97 }, { 16, 109 }, { 8, 109 }, { 8, 97 }, { 8, 89 }, { 8, 81 }, + { 8, 73 }, { 8, 65 }, { 8, 57 }, { 16, 57 }, { 8, 49 }, { 8, 41 }, + { 24, 45 }, { 32, 41 }, { 32, 49 }, { 32, 57 }, { 32, 65 }, { 32, 73 }, + { 32, 81 }, { 40, 83 }, { 40, 73 }, { 40, 63 }, { 40, 51 }, { 44, 43 }, + { 44, 35 }, { 44, 27 }, { 32, 25 }, { 24, 25 }, { 16, 25 }, { 16, 17 }, + { 24, 17 }, { 32, 17 }, { 44, 11 }, { 56, 9 }, { 56, 17 }, { 56, 25 }, + { 56, 33 }, { 56, 41 }, { 64, 41 }, { 72, 41 }, { 72, 49 }, { 56, 49 }, + { 48, 51 }, { 56, 57 }, { 56, 65 }, { 48, 63 }, { 48, 73 }, { 56, 73 }, + { 56, 81 }, { 48, 83 }, { 56, 89 }, { 56, 97 }, { 104, 97 }, { 104, 105 }, + { 104, 113 }, { 104, 121 }, { 104, 129 }, { 104, 137 }, { 104, 145 }, { 116, 145 }, + { 124, 145 }, { 132, 145 }, { 132, 137 }, { 140, 137 }, { 148, 137 }, { 156, 137 }, + { 164, 137 }, { 172, 125 }, { 172, 117 }, { 172, 109 }, { 172, 101 }, { 172, 93 }, + { 172, 85 }, { 180, 85 }, { 180, 77 }, { 180, 69 }, { 180, 61 }, { 180, 53 }, + { 172, 53 }, { 172, 61 }, { 172, 69 }, { 172, 77 }, { 164, 81 }, { 148, 85 }, + { 124, 85 }, { 124, 93 }, { 124, 109 }, { 124, 125 }, { 124, 117 }, { 124, 101 }, + { 104, 89 }, { 104, 81 }, { 104, 73 }, { 104, 65 }, { 104, 49 }, { 104, 41 }, + { 104, 33 }, { 104, 25 }, { 104, 17 }, { 92, 9 }, { 80, 9 }, { 72, 9 }, + { 64, 21 }, { 72, 25 }, { 80, 25 }, { 80, 25 }, { 80, 41 }, { 88, 49 }, + { 104, 57 }, { 124, 69 }, { 124, 77 }, { 132, 81 }, { 140, 65 }, { 132, 61 }, + { 124, 61 }, { 124, 53 }, { 124, 45 }, { 124, 37 }, { 124, 29 }, { 132, 21 }, + { 124, 21 }, { 120, 9 }, { 128, 9 }, { 136, 9 }, { 148, 9 }, { 162, 9 }, + { 156, 25 }, { 172, 21 }, { 180, 21 }, { 180, 29 }, { 172, 29 }, { 172, 37 }, + { 172, 45 }, { 180, 45 }, { 180, 37 }, { 188, 41 }, { 196, 49 }, { 204, 57 }, + { 212, 65 }, { 220, 73 }, { 228, 69 }, { 228, 77 }, { 236, 77 }, { 236, 69 }, + { 236, 61 }, { 228, 61 }, { 228, 53 }, { 236, 53 }, { 236, 45 }, { 228, 45 }, + { 228, 37 }, { 236, 37 }, { 236, 29 }, { 228, 29 }, { 228, 21 }, { 236, 21 }, + { 252, 21 }, { 260, 29 }, { 260, 37 }, { 260, 45 }, { 260, 53 }, { 260, 61 }, + { 260, 69 }, { 260, 77 }, { 276, 77 }, { 276, 69 }, { 276, 61 }, { 276, 53 }, + { 284, 53 }, { 284, 61 }, { 284, 69 }, { 284, 77 }, { 284, 85 }, { 284, 93 }, + { 284, 101 }, { 288, 109 }, { 280, 109 }, { 276, 101 }, { 276, 93 }, { 276, 85 }, + { 268, 97 }, { 260, 109 }, { 252, 101 }, { 260, 93 }, { 260, 85 }, { 236, 85 }, + { 228, 85 }, { 228, 93 }, { 236, 93 }, { 236, 101 }, { 228, 101 }, { 228, 109 }, + { 228, 117 }, { 228, 125 }, { 220, 125 }, { 212, 117 }, { 204, 109 }, { 196, 101 }, + { 188, 93 }, { 180, 93 }, { 180, 101 }, { 180, 109 }, { 180, 117 }, { 180, 125 }, + { 196, 145 }, { 204, 145 }, { 212, 145 }, { 220, 145 }, { 228, 145 }, { 236, 145 }, + { 246, 141 }, { 252, 125 }, { 260, 129 }, { 280, 133 }, }; public int VehicleNumber = 1; public int Depot = 0; @@ -86,18 +86,18 @@ public class TspCircuitBoard { /// positions and computes the Euclidean distance between the two /// positions of two different indices. /// - static long[, ] ComputeEuclideanDistanceMatrix(in int[, ] locations) { + static long[,] ComputeEuclideanDistanceMatrix(in int[,] locations) { // Calculate the distance matrix using Euclidean distance. int locationNumber = locations.GetLength(0); - long[, ] distanceMatrix = new long[locationNumber, locationNumber]; + long[,] distanceMatrix = new long[locationNumber, locationNumber]; for (int fromNode = 0; fromNode < locationNumber; fromNode++) { for (int toNode = 0; toNode < locationNumber; toNode++) { if (fromNode == toNode) distanceMatrix[fromNode, toNode] = 0; else - distanceMatrix[fromNode, toNode] = (long) Math.Sqrt( - Math.Pow(locations[toNode, 0] - locations[fromNode, 0], 2) + - Math.Pow(locations[toNode, 1] - locations[fromNode, 1], 2)); + distanceMatrix[fromNode, toNode] = + (long)Math.Sqrt(Math.Pow(locations[toNode, 0] - locations[fromNode, 0], 2) + + Math.Pow(locations[toNode, 1] - locations[fromNode, 1], 2)); } } return distanceMatrix; @@ -108,8 +108,7 @@ public class TspCircuitBoard { /// /// Print the solution. /// - static void PrintSolution(in RoutingModel routing, - in RoutingIndexManager manager, + static void PrintSolution(in RoutingModel routing, in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine("Objective: {0}", solution.ObjectiveValue()); // Inspect solution. @@ -117,12 +116,12 @@ public class TspCircuitBoard { long routeDistance = 0; var index = routing.Start(0); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Route distance: {0}m", routeDistance); } // [END solution_printer] @@ -135,8 +134,8 @@ public class TspCircuitBoard { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.Locations.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.Locations.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -146,14 +145,13 @@ public class TspCircuitBoard { // Define cost of each arc. // [START transit_callback] - long[, ] distanceMatrix = ComputeEuclideanDistanceMatrix(data.Locations); - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return distanceMatrix[fromNode, toNode]; - }); + long[,] distanceMatrix = ComputeEuclideanDistanceMatrix(data.Locations); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return distanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // [START arc_cost] @@ -164,8 +162,7 @@ public class TspCircuitBoard { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/TspCities.cs b/ortools/constraint_solver/samples/TspCities.cs index 146438e0d8..bc1a30db2b 100644 --- a/ortools/constraint_solver/samples/TspCities.cs +++ b/ortools/constraint_solver/samples/TspCities.cs @@ -24,23 +24,20 @@ using Google.OrTools.ConstraintSolver; public class TspCities { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 2451, 713, 1018, 1631, 1374, 2408, 213, 2571, 875, 1420, 2145, - 1972}, - {2451, 0, 1745, 1524, 831, 1240, 959, 2596, 403, 1589, 1374, 357, 579}, - {713, 1745, 0, 355, 920, 803, 1737, 851, 1858, 262, 940, 1453, 1260}, - {1018, 1524, 355, 0, 700, 862, 1395, 1123, 1584, 466, 1056, 1280, 987}, - {1631, 831, 920, 700, 0, 663, 1021, 1769, 949, 796, 879, 586, 371}, - {1374, 1240, 803, 862, 663, 0, 1681, 1551, 1765, 547, 225, 887, 999}, - {2408, 959, 1737, 1395, 1021, 1681, 0, 2493, 678, 1724, 1891, 1114, - 701}, - {213, 2596, 851, 1123, 1769, 1551, 2493, 0, 2699, 1038, 1605, 2300, - 2099}, - {2571, 403, 1858, 1584, 949, 1765, 678, 2699, 0, 1744, 1645, 653, 600}, - {875, 1589, 262, 466, 796, 547, 1724, 1038, 1744, 0, 679, 1272, 1162}, - {1420, 1374, 940, 1056, 879, 225, 1891, 1605, 1645, 679, 0, 1017, 1200}, - {2145, 357, 1453, 1280, 586, 887, 1114, 2300, 653, 1272, 1017, 0, 504}, - {1972, 579, 1260, 987, 371, 999, 701, 2099, 600, 1162, 1200, 504, 0}, + public long[,] DistanceMatrix = { + { 0, 2451, 713, 1018, 1631, 1374, 2408, 213, 2571, 875, 1420, 2145, 1972 }, + { 2451, 0, 1745, 1524, 831, 1240, 959, 2596, 403, 1589, 1374, 357, 579 }, + { 713, 1745, 0, 355, 920, 803, 1737, 851, 1858, 262, 940, 1453, 1260 }, + { 1018, 1524, 355, 0, 700, 862, 1395, 1123, 1584, 466, 1056, 1280, 987 }, + { 1631, 831, 920, 700, 0, 663, 1021, 1769, 949, 796, 879, 586, 371 }, + { 1374, 1240, 803, 862, 663, 0, 1681, 1551, 1765, 547, 225, 887, 999 }, + { 2408, 959, 1737, 1395, 1021, 1681, 0, 2493, 678, 1724, 1891, 1114, 701 }, + { 213, 2596, 851, 1123, 1769, 1551, 2493, 0, 2699, 1038, 1605, 2300, 2099 }, + { 2571, 403, 1858, 1584, 949, 1765, 678, 2699, 0, 1744, 1645, 653, 600 }, + { 875, 1589, 262, 466, 796, 547, 1724, 1038, 1744, 0, 679, 1272, 1162 }, + { 1420, 1374, 940, 1056, 879, 225, 1891, 1605, 1645, 679, 0, 1017, 1200 }, + { 2145, 357, 1453, 1280, 586, 887, 1114, 2300, 653, 1272, 1017, 0, 504 }, + { 1972, 579, 1260, 987, 371, 999, 701, 2099, 600, 1162, 1200, 504, 0 }, }; public int VehicleNumber = 1; public int Depot = 0; @@ -51,8 +48,7 @@ public class TspCities { /// /// Print the solution. /// - static void PrintSolution(in RoutingModel routing, - in RoutingIndexManager manager, + static void PrintSolution(in RoutingModel routing, in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine("Objective: {0} miles", solution.ObjectiveValue()); // Inspect solution. @@ -60,12 +56,12 @@ public class TspCities { long routeDistance = 0; var index = routing.Start(0); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Route distance: {0}miles", routeDistance); } // [END solution_printer] @@ -78,8 +74,8 @@ public class TspCities { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -88,13 +84,12 @@ public class TspCities { // [END routing_model] // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -106,8 +101,7 @@ public class TspCities { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/TspDistanceMatrix.cs b/ortools/constraint_solver/samples/TspDistanceMatrix.cs index de6dfed9c8..3133ad0f06 100644 --- a/ortools/constraint_solver/samples/TspDistanceMatrix.cs +++ b/ortools/constraint_solver/samples/TspDistanceMatrix.cs @@ -24,41 +24,25 @@ using Google.OrTools.ConstraintSolver; public class TspDistanceMatrix { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; public int VehicleNumber = 1; public int Depot = 0; }; @@ -68,8 +52,7 @@ public class TspDistanceMatrix { /// /// Print the solution. /// - static void PrintSolution(in RoutingModel routing, - in RoutingIndexManager manager, + static void PrintSolution(in RoutingModel routing, in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine("Objective: {0}", solution.ObjectiveValue()); // Inspect solution. @@ -77,12 +60,12 @@ public class TspDistanceMatrix { long routeDistance = 0; var index = routing.Start(0); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); } // [END solution_printer] @@ -95,8 +78,8 @@ public class TspDistanceMatrix { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -106,13 +89,12 @@ public class TspDistanceMatrix { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -124,8 +106,7 @@ public class TspDistanceMatrix { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/Vrp.cs b/ortools/constraint_solver/samples/Vrp.cs index 35f58ec6a6..318f78275c 100644 --- a/ortools/constraint_solver/samples/Vrp.cs +++ b/ortools/constraint_solver/samples/Vrp.cs @@ -24,41 +24,25 @@ using Google.OrTools.ConstraintSolver; public class Vrp { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; public int VehicleNumber = 4; public int Depot = 0; }; @@ -69,8 +53,7 @@ public class Vrp { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { Console.WriteLine("Objective: {0}", solution.ObjectiveValue()); // Inspect solution. long totalDistance = 0; @@ -79,12 +62,12 @@ public class Vrp { long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; } @@ -100,8 +83,8 @@ public class Vrp { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -111,13 +94,12 @@ public class Vrp { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -129,8 +111,7 @@ public class Vrp { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpCapacity.cs b/ortools/constraint_solver/samples/VrpCapacity.cs index c8e3fe7752..2836caa3e9 100644 --- a/ortools/constraint_solver/samples/VrpCapacity.cs +++ b/ortools/constraint_solver/samples/VrpCapacity.cs @@ -25,44 +25,28 @@ using Google.Protobuf.WellKnownTypes; // Duration public class VrpCapacity { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; // [START demands_capacities] - public long[] Demands = {0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8}; - public long[] VehicleCapacities = {15, 15, 15, 15}; + public long[] Demands = { 0, 1, 1, 2, 4, 2, 4, 8, 8, 1, 2, 1, 2, 4, 4, 8, 8 }; + public long[] VehicleCapacities = { 15, 15, 15, 15 }; // [END demands_capacities] public int VehicleNumber = 4; public int Depot = 0; @@ -74,8 +58,7 @@ public class VrpCapacity { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { // Inspect solution. long totalDistance = 0; long totalLoad = 0; @@ -92,7 +75,7 @@ public class VrpCapacity { index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; totalLoad += routeLoad; @@ -110,8 +93,8 @@ public class VrpCapacity { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -121,13 +104,12 @@ public class VrpCapacity { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -137,28 +119,25 @@ public class VrpCapacity { // Add Capacity constraint. // [START capacity_constraint] - int demandCallbackIndex = - routing.RegisterUnaryTransitCallback((long fromIndex) => { - // Convert from routing variable Index to demand NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - return data.Demands[fromNode]; - }); - routing.AddDimensionWithVehicleCapacity( - demandCallbackIndex, 0, // null capacity slack - data.VehicleCapacities, // vehicle maximum capacities - true, // start cumul to zero - "Capacity"); + int demandCallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => { + // Convert from routing variable Index to demand NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + return data.Demands[fromNode]; + }); + routing.AddDimensionWithVehicleCapacity(demandCallbackIndex, 0, // null capacity slack + data.VehicleCapacities, // vehicle maximum capacities + true, // start cumul to zero + "Capacity"); // [END capacity_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch; - searchParameters.TimeLimit = new Duration{Seconds = 1}; + searchParameters.TimeLimit = new Duration { Seconds = 1 }; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpDropNodes.cs b/ortools/constraint_solver/samples/VrpDropNodes.cs index d87207a78c..b4ba550c6d 100644 --- a/ortools/constraint_solver/samples/VrpDropNodes.cs +++ b/ortools/constraint_solver/samples/VrpDropNodes.cs @@ -25,44 +25,28 @@ using Google.Protobuf.WellKnownTypes; // Duration public class VrpDropNodes { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; // [START demands_capacities] - public long[] Demands = {0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8}; - public long[] VehicleCapacities = {15, 15, 15, 15}; + public long[] Demands = { 0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8 }; + public long[] VehicleCapacities = { 15, 15, 15, 15 }; // [END demands_capacities] public int VehicleNumber = 4; public int Depot = 0; @@ -74,8 +58,7 @@ public class VrpDropNodes { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { // Display dropped nodes. string droppedNodes = "Dropped nodes:"; for (int index = 0; index < routing.Size(); ++index) { @@ -103,7 +86,7 @@ public class VrpDropNodes { index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; totalLoad += routeLoad; @@ -121,8 +104,8 @@ public class VrpDropNodes { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -132,13 +115,12 @@ public class VrpDropNodes { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -148,21 +130,19 @@ public class VrpDropNodes { // Add Capacity constraint. // [START capacity_constraint] - int demandCallbackIndex = - routing.RegisterUnaryTransitCallback((long fromIndex) => { - // Convert from routing variable Index to demand NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - return data.Demands[fromNode]; - }); - routing.AddDimensionWithVehicleCapacity( - demandCallbackIndex, 0, // null capacity slack - data.VehicleCapacities, // vehicle maximum capacities - true, // start cumul to zero - "Capacity"); + int demandCallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => { + // Convert from routing variable Index to demand NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + return data.Demands[fromNode]; + }); + routing.AddDimensionWithVehicleCapacity(demandCallbackIndex, 0, // null capacity slack + data.VehicleCapacities, // vehicle maximum capacities + true, // start cumul to zero + "Capacity"); // Allow to drop nodes. long penalty = 1000; for (int i = 1; i < data.DistanceMatrix.GetLength(0); ++i) { - routing.AddDisjunction(new long[]{manager.NodeToIndex(i)}, penalty); + routing.AddDisjunction(new long[] { manager.NodeToIndex(i) }, penalty); } // [END capacity_constraint] @@ -170,11 +150,10 @@ public class VrpDropNodes { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch; - searchParameters.TimeLimit = new Duration{Seconds = 1}; + searchParameters.TimeLimit = new Duration { Seconds = 1 }; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpGlobalSpan.cs b/ortools/constraint_solver/samples/VrpGlobalSpan.cs index 165081985f..1dff0691e5 100644 --- a/ortools/constraint_solver/samples/VrpGlobalSpan.cs +++ b/ortools/constraint_solver/samples/VrpGlobalSpan.cs @@ -24,41 +24,25 @@ using Google.OrTools.ConstraintSolver; public class VrpGlobalSpan { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; public int VehicleNumber = 4; public int Depot = 0; }; @@ -69,8 +53,7 @@ public class VrpGlobalSpan { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { @@ -78,12 +61,12 @@ public class VrpGlobalSpan { long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); maxRouteDistance = Math.Max(routeDistance, maxRouteDistance); } @@ -99,8 +82,8 @@ public class VrpGlobalSpan { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] @@ -111,13 +94,12 @@ public class VrpGlobalSpan { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -130,8 +112,7 @@ public class VrpGlobalSpan { routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -139,8 +120,7 @@ public class VrpGlobalSpan { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpInitialRoutes.cs b/ortools/constraint_solver/samples/VrpInitialRoutes.cs index 3812edca94..f7030afcb1 100644 --- a/ortools/constraint_solver/samples/VrpInitialRoutes.cs +++ b/ortools/constraint_solver/samples/VrpInitialRoutes.cs @@ -24,48 +24,31 @@ using Google.OrTools.ConstraintSolver; public class InitialRoutes { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}, + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 }, }; // [START initial_routes] public long[][] InitialRoutes = { - new long[]{8, 16, 14, 13, 12, 11}, - new long[]{3, 4, 9, 10}, - new long[]{15, 1}, - new long[]{7, 5, 2, 6}, + new long[] { 8, 16, 14, 13, 12, 11 }, + new long[] { 3, 4, 9, 10 }, + new long[] { 15, 1 }, + new long[] { 7, 5, 2, 6 }, }; // [END initial_routes] public int VehicleNumber = 4; @@ -78,8 +61,7 @@ public class InitialRoutes { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { @@ -87,12 +69,12 @@ public class InitialRoutes { long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}", routeDistance); maxRouteDistance = Math.Max(routeDistance, maxRouteDistance); } @@ -108,8 +90,8 @@ public class InitialRoutes { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -119,13 +101,12 @@ public class InitialRoutes { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -138,15 +119,13 @@ public class InitialRoutes { routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] // Get inital solution from routes. // [START print_initial_solution] - Assignment initialSolution = - routing.ReadAssignmentFromRoutes(data.InitialRoutes, true); + Assignment initialSolution = routing.ReadAssignmentFromRoutes(data.InitialRoutes, true); // Print initial solution on console. Console.WriteLine("Initial solution:"); PrintSolution(data, routing, manager, initialSolution); diff --git a/ortools/constraint_solver/samples/VrpPickupDelivery.cs b/ortools/constraint_solver/samples/VrpPickupDelivery.cs index c5b9279822..529a710d1a 100644 --- a/ortools/constraint_solver/samples/VrpPickupDelivery.cs +++ b/ortools/constraint_solver/samples/VrpPickupDelivery.cs @@ -24,46 +24,29 @@ using Google.OrTools.ConstraintSolver; public class VrpPickupDelivery { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; // [START pickups_deliveries] public int[][] PickupsDeliveries = { - new int[]{1, 6}, new int[]{2, 10}, new int[]{4, 3}, - new int[]{5, 9}, new int[]{7, 8}, new int[]{15, 11}, - new int[]{13, 12}, new int[]{16, 14}, + new int[] { 1, 6 }, new int[] { 2, 10 }, new int[] { 4, 3 }, new int[] { 5, 9 }, + new int[] { 7, 8 }, new int[] { 15, 11 }, new int[] { 13, 12 }, new int[] { 16, 14 }, }; // [END pickups_deliveries] public int VehicleNumber = 4; @@ -76,20 +59,19 @@ public class VrpPickupDelivery { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { long totalDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { Console.WriteLine("Route for Vehicle {0}:", i); long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; } @@ -105,8 +87,8 @@ public class VrpPickupDelivery { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] @@ -117,13 +99,12 @@ public class VrpPickupDelivery { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -136,8 +117,7 @@ public class VrpPickupDelivery { routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -145,16 +125,13 @@ public class VrpPickupDelivery { // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int i = 0; i < data.PickupsDeliveries.GetLength(0); i++) { - long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [0]); - long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [1]); + long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries[i][0]); + long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries[i][1]); routing.AddPickupAndDelivery(pickupIndex, deliveryIndex); - solver.Add(solver.MakeEquality(routing.VehicleVar(pickupIndex), - routing.VehicleVar(deliveryIndex))); solver.Add( - solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), - distanceDimension.CumulVar(deliveryIndex))); + solver.MakeEquality(routing.VehicleVar(pickupIndex), routing.VehicleVar(deliveryIndex))); + solver.Add(solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), + distanceDimension.CumulVar(deliveryIndex))); } // [END pickup_delivery_constraint] @@ -162,8 +139,7 @@ public class VrpPickupDelivery { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpPickupDeliveryFifo.cs b/ortools/constraint_solver/samples/VrpPickupDeliveryFifo.cs index 751bf8f8d0..648eb7f814 100644 --- a/ortools/constraint_solver/samples/VrpPickupDeliveryFifo.cs +++ b/ortools/constraint_solver/samples/VrpPickupDeliveryFifo.cs @@ -24,46 +24,29 @@ using Google.OrTools.ConstraintSolver; public class VrpPickupDeliveryFifo { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; // [START pickups_deliveries] public int[][] PickupsDeliveries = { - new int[]{1, 6}, new int[]{2, 10}, new int[]{4, 3}, - new int[]{5, 9}, new int[]{7, 8}, new int[]{15, 11}, - new int[]{13, 12}, new int[]{16, 14}, + new int[] { 1, 6 }, new int[] { 2, 10 }, new int[] { 4, 3 }, new int[] { 5, 9 }, + new int[] { 7, 8 }, new int[] { 15, 11 }, new int[] { 13, 12 }, new int[] { 16, 14 }, }; // [END pickups_deliveries] public int VehicleNumber = 4; @@ -76,20 +59,19 @@ public class VrpPickupDeliveryFifo { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { long totalDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { Console.WriteLine("Route for Vehicle {0}:", i); long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; } @@ -105,8 +87,8 @@ public class VrpPickupDeliveryFifo { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] @@ -117,13 +99,12 @@ public class VrpPickupDeliveryFifo { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -136,8 +117,7 @@ public class VrpPickupDeliveryFifo { routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -145,27 +125,22 @@ public class VrpPickupDeliveryFifo { // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int i = 0; i < data.PickupsDeliveries.GetLength(0); i++) { - long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [0]); - long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [1]); + long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries[i][0]); + long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries[i][1]); routing.AddPickupAndDelivery(pickupIndex, deliveryIndex); - solver.Add(solver.MakeEquality(routing.VehicleVar(pickupIndex), - routing.VehicleVar(deliveryIndex))); solver.Add( - solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), - distanceDimension.CumulVar(deliveryIndex))); + solver.MakeEquality(routing.VehicleVar(pickupIndex), routing.VehicleVar(deliveryIndex))); + solver.Add(solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), + distanceDimension.CumulVar(deliveryIndex))); } - routing.SetPickupAndDeliveryPolicyOfAllVehicles( - RoutingModel.PICKUP_AND_DELIVERY_FIFO); + routing.SetPickupAndDeliveryPolicyOfAllVehicles(RoutingModel.PICKUP_AND_DELIVERY_FIFO); // [END pickup_delivery_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpPickupDeliveryLifo.cs b/ortools/constraint_solver/samples/VrpPickupDeliveryLifo.cs index 2e6ee8d249..2abb871522 100644 --- a/ortools/constraint_solver/samples/VrpPickupDeliveryLifo.cs +++ b/ortools/constraint_solver/samples/VrpPickupDeliveryLifo.cs @@ -24,46 +24,29 @@ using Google.OrTools.ConstraintSolver; public class VrpPickupDeliveryLifo { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; // [START pickups_deliveries] public int[][] PickupsDeliveries = { - new int[]{1, 6}, new int[]{2, 10}, new int[]{4, 3}, - new int[]{5, 9}, new int[]{7, 8}, new int[]{15, 11}, - new int[]{13, 12}, new int[]{16, 14}, + new int[] { 1, 6 }, new int[] { 2, 10 }, new int[] { 4, 3 }, new int[] { 5, 9 }, + new int[] { 7, 8 }, new int[] { 15, 11 }, new int[] { 13, 12 }, new int[] { 16, 14 }, }; // [END pickups_deliveries] public int VehicleNumber = 4; @@ -76,20 +59,19 @@ public class VrpPickupDeliveryLifo { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { long totalDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { Console.WriteLine("Route for Vehicle {0}:", i); long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; } @@ -105,8 +87,8 @@ public class VrpPickupDeliveryLifo { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -116,13 +98,12 @@ public class VrpPickupDeliveryLifo { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -135,8 +116,7 @@ public class VrpPickupDeliveryLifo { routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -144,27 +124,22 @@ public class VrpPickupDeliveryLifo { // [START pickup_delivery_constraint] Solver solver = routing.solver(); for (int i = 0; i < data.PickupsDeliveries.GetLength(0); i++) { - long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [0]); - long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries [i] - [1]); + long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries[i][0]); + long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries[i][1]); routing.AddPickupAndDelivery(pickupIndex, deliveryIndex); - solver.Add(solver.MakeEquality(routing.VehicleVar(pickupIndex), - routing.VehicleVar(deliveryIndex))); solver.Add( - solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), - distanceDimension.CumulVar(deliveryIndex))); + solver.MakeEquality(routing.VehicleVar(pickupIndex), routing.VehicleVar(deliveryIndex))); + solver.Add(solver.MakeLessOrEqual(distanceDimension.CumulVar(pickupIndex), + distanceDimension.CumulVar(deliveryIndex))); } - routing.SetPickupAndDeliveryPolicyOfAllVehicles( - RoutingModel.PICKUP_AND_DELIVERY_LIFO); + routing.SetPickupAndDeliveryPolicyOfAllVehicles(RoutingModel.PICKUP_AND_DELIVERY_LIFO); // [END pickup_delivery_constraint] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpResources.cs b/ortools/constraint_solver/samples/VrpResources.cs index 8352af66bf..23dc227058 100644 --- a/ortools/constraint_solver/samples/VrpResources.cs +++ b/ortools/constraint_solver/samples/VrpResources.cs @@ -25,43 +25,43 @@ using Google.OrTools.ConstraintSolver; public class VrpResources { // [START data_model] class DataModel { - public long[, ] TimeMatrix = { - {0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7}, - {6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14}, - {9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9}, - {8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16}, - {7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14}, - {3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8}, - {6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5}, - {2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10}, - {3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6}, - {2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5}, - {6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4}, - {6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10}, - {4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8}, - {4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6}, - {5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2}, - {9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9}, - {7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0}, + public long[,] TimeMatrix = { + { 0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7 }, + { 6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14 }, + { 9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9 }, + { 8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16 }, + { 7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14 }, + { 3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8 }, + { 6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5 }, + { 2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10 }, + { 3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6 }, + { 2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5 }, + { 6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4 }, + { 6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10 }, + { 4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8 }, + { 4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6 }, + { 5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2 }, + { 9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9 }, + { 7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0 }, }; - public long[, ] TimeWindows = { - {0, 5}, // depot - {7, 12}, // 1 - {10, 15}, // 2 - {5, 14}, // 3 - {5, 13}, // 4 - {0, 5}, // 5 - {5, 10}, // 6 - {0, 10}, // 7 - {5, 10}, // 8 - {0, 5}, // 9 - {10, 16}, // 10 - {10, 15}, // 11 - {0, 5}, // 12 - {5, 10}, // 13 - {7, 12}, // 14 - {10, 15}, // 15 - {5, 15}, // 16 + public long[,] TimeWindows = { + { 0, 5 }, // depot + { 7, 12 }, // 1 + { 10, 15 }, // 2 + { 5, 14 }, // 3 + { 5, 13 }, // 4 + { 0, 5 }, // 5 + { 5, 10 }, // 6 + { 0, 10 }, // 7 + { 5, 10 }, // 8 + { 0, 5 }, // 9 + { 10, 16 }, // 10 + { 10, 15 }, // 11 + { 0, 5 }, // 12 + { 5, 10 }, // 13 + { 7, 12 }, // 14 + { 10, 15 }, // 15 + { 5, 15 }, // 16 }; public int VehicleNumber = 4; // [START resources_data] @@ -78,8 +78,7 @@ public class VrpResources { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { RoutingDimension timeDimension = routing.GetMutableDimension("Time"); // Inspect solution. long totalTime = 0; @@ -88,13 +87,13 @@ public class VrpResources { var index = routing.Start(i); while (routing.IsEnd(index) == false) { var timeVar = timeDimension.CumulVar(index); - Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), - solution.Min(timeVar), solution.Max(timeVar)); + Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), solution.Min(timeVar), + solution.Max(timeVar)); index = solution.Value(routing.NextVar(index)); } var endTimeVar = timeDimension.CumulVar(index); - Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), - solution.Min(endTimeVar), solution.Max(endTimeVar)); + Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), solution.Min(endTimeVar), + solution.Max(endTimeVar)); Console.WriteLine("Time of the route: {0}min", solution.Min(endTimeVar)); totalTime += solution.Min(endTimeVar); } @@ -110,8 +109,8 @@ public class VrpResources { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.TimeMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.TimeMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -121,13 +120,12 @@ public class VrpResources { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.TimeMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.TimeMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -146,14 +144,12 @@ public class VrpResources { // Add time window constraints for each location except depot. for (int i = 1; i < data.TimeWindows.GetLength(0); ++i) { long index = manager.NodeToIndex(i); - timeDimension.CumulVar(index).SetRange(data.TimeWindows[i, 0], - data.TimeWindows[i, 1]); + timeDimension.CumulVar(index).SetRange(data.TimeWindows[i, 0], data.TimeWindows[i, 1]); } // Add time window constraints for each vehicle start node. for (int i = 0; i < data.VehicleNumber; ++i) { long index = routing.Start(i); - timeDimension.CumulVar(index).SetRange(data.TimeWindows[0, 0], - data.TimeWindows[0, 1]); + timeDimension.CumulVar(index).SetRange(data.TimeWindows[0, 0], data.TimeWindows[0, 1]); } // [END time_constraint] @@ -164,28 +160,23 @@ public class VrpResources { for (int i = 0; i < data.VehicleNumber; ++i) { // Add load duration at start of routes intervals[2 * i] = solver.MakeFixedDurationIntervalVar( - timeDimension.CumulVar(routing.Start(i)), data.VehicleLoadTime, - "depot_interval"); + timeDimension.CumulVar(routing.Start(i)), data.VehicleLoadTime, "depot_interval"); // Add unload duration at end of routes. intervals[2 * i + 1] = solver.MakeFixedDurationIntervalVar( - timeDimension.CumulVar(routing.End(i)), data.VehicleUnloadTime, - "depot_interval"); + timeDimension.CumulVar(routing.End(i)), data.VehicleUnloadTime, "depot_interval"); } // [END depot_load_time] // [START depot_capacity] long[] depot_usage = Enumerable.Repeat(1, intervals.Length).ToArray(); - solver.Add(solver.MakeCumulative(intervals, depot_usage, data.DepotCapacity, - "depot")); + solver.Add(solver.MakeCumulative(intervals, depot_usage, data.DepotCapacity, "depot")); // [END depot_capacity] // Instantiate route start and end times to produce feasible times. // [START depot_start_end_times] for (int i = 0; i < data.VehicleNumber; ++i) { - routing.AddVariableMinimizedByFinalizer( - timeDimension.CumulVar(routing.Start(i))); - routing.AddVariableMinimizedByFinalizer( - timeDimension.CumulVar(routing.End(i))); + routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.Start(i))); + routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.End(i))); } // [END depot_start_end_times] @@ -193,8 +184,7 @@ public class VrpResources { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpStartsEnds.cs b/ortools/constraint_solver/samples/VrpStartsEnds.cs index 59aad0aa58..457433032d 100644 --- a/ortools/constraint_solver/samples/VrpStartsEnds.cs +++ b/ortools/constraint_solver/samples/VrpStartsEnds.cs @@ -24,45 +24,29 @@ using Google.OrTools.ConstraintSolver; public class VrpStartsEnds { // [START data_model] class DataModel { - public long[, ] DistanceMatrix = { - {0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, - 468, 776, 662}, - {548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, - 1016, 868, 1210}, - {776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, - 788, 1552, 754}, - {696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, - 1164, 560, 1358}, - {582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, - 1050, 674, 1244}, - {274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, - 514, 1050, 708}, - {502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, - 514, 1278, 480}, - {194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, - 662, 742, 856}, - {308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, - 320, 1084, 514}, - {194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, - 274, 810, 468}, - {536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, - 388, 1152, 354}, - {502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, - 650, 274, 844}, - {388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, - 536, 388, 730}, - {354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, - 342, 422, 536}, - {468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, - 342, 0, 764, 194}, - {776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, - 422, 764, 0, 798}, - {662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, - 536, 194, 798, 0}}; + public long[,] DistanceMatrix = { + { 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 }, + { 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 }, + { 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 }, + { 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 }, + { 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 }, + { 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 }, + { 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 }, + { 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 }, + { 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 }, + { 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 }, + { 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 }, + { 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 }, + { 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 }, + { 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 }, + { 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 }, + { 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 }, + { 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 } + }; public int VehicleNumber = 4; // [START starts_ends] - public int[] Starts = {1, 2, 15, 16}; - public int[] Ends = {0, 0, 0, 0}; + public int[] Starts = { 1, 2, 15, 16 }; + public int[] Ends = { 0, 0, 0, 0 }; // [END starts_ends] }; // [END data_model] @@ -72,8 +56,7 @@ public class VrpStartsEnds { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { @@ -81,12 +64,12 @@ public class VrpStartsEnds { long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); maxRouteDistance = Math.Max(routeDistance, maxRouteDistance); } @@ -102,9 +85,8 @@ public class VrpStartsEnds { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = - new RoutingIndexManager(data.DistanceMatrix.GetLength(0), - data.VehicleNumber, data.Starts, data.Ends); + RoutingIndexManager manager = new RoutingIndexManager( + data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Starts, data.Ends); // [END index_manager] // Create Routing Model. @@ -114,13 +96,12 @@ public class VrpStartsEnds { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.DistanceMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.DistanceMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -133,8 +114,7 @@ public class VrpStartsEnds { routing.AddDimension(transitCallbackIndex, 0, 2000, true, // start cumul to zero "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -142,8 +122,7 @@ public class VrpStartsEnds { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpTimeWindows.cs b/ortools/constraint_solver/samples/VrpTimeWindows.cs index 39f0bc5a91..8557b66a5b 100644 --- a/ortools/constraint_solver/samples/VrpTimeWindows.cs +++ b/ortools/constraint_solver/samples/VrpTimeWindows.cs @@ -25,43 +25,43 @@ using Google.OrTools.ConstraintSolver; public class VrpTimeWindows { // [START data_model] class DataModel { - public long[, ] TimeMatrix = { - {0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7}, - {6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14}, - {9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9}, - {8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16}, - {7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14}, - {3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8}, - {6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5}, - {2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10}, - {3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6}, - {2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5}, - {6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4}, - {6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10}, - {4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8}, - {4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6}, - {5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2}, - {9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9}, - {7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0}, + public long[,] TimeMatrix = { + { 0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7 }, + { 6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14 }, + { 9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9 }, + { 8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16 }, + { 7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14 }, + { 3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8 }, + { 6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5 }, + { 2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10 }, + { 3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6 }, + { 2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5 }, + { 6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4 }, + { 6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10 }, + { 4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8 }, + { 4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6 }, + { 5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2 }, + { 9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9 }, + { 7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0 }, }; - public long[, ] TimeWindows = { - {0, 5}, // depot - {7, 12}, // 1 - {10, 15}, // 2 - {16, 18}, // 3 - {10, 13}, // 4 - {0, 5}, // 5 - {5, 10}, // 6 - {0, 4}, // 7 - {5, 10}, // 8 - {0, 3}, // 9 - {10, 16}, // 10 - {10, 15}, // 11 - {0, 5}, // 12 - {5, 10}, // 13 - {7, 8}, // 14 - {10, 15}, // 15 - {11, 15}, // 16 + public long[,] TimeWindows = { + { 0, 5 }, // depot + { 7, 12 }, // 1 + { 10, 15 }, // 2 + { 16, 18 }, // 3 + { 10, 13 }, // 4 + { 0, 5 }, // 5 + { 5, 10 }, // 6 + { 0, 4 }, // 7 + { 5, 10 }, // 8 + { 0, 3 }, // 9 + { 10, 16 }, // 10 + { 10, 15 }, // 11 + { 0, 5 }, // 12 + { 5, 10 }, // 13 + { 7, 8 }, // 14 + { 10, 15 }, // 15 + { 11, 15 }, // 16 }; public int VehicleNumber = 4; public int Depot = 0; @@ -73,8 +73,7 @@ public class VrpTimeWindows { /// Print the solution. /// static void PrintSolution(in DataModel data, in RoutingModel routing, - in RoutingIndexManager manager, - in Assignment solution) { + in RoutingIndexManager manager, in Assignment solution) { RoutingDimension timeDimension = routing.GetMutableDimension("Time"); // Inspect solution. long totalTime = 0; @@ -83,13 +82,13 @@ public class VrpTimeWindows { var index = routing.Start(i); while (routing.IsEnd(index) == false) { var timeVar = timeDimension.CumulVar(index); - Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), - solution.Min(timeVar), solution.Max(timeVar)); + Console.Write("{0} Time({1},{2}) -> ", manager.IndexToNode(index), solution.Min(timeVar), + solution.Max(timeVar)); index = solution.Value(routing.NextVar(index)); } var endTimeVar = timeDimension.CumulVar(index); - Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), - solution.Min(endTimeVar), solution.Max(endTimeVar)); + Console.WriteLine("{0} Time({1},{2})", manager.IndexToNode(index), solution.Min(endTimeVar), + solution.Max(endTimeVar)); Console.WriteLine("Time of the route: {0}min", solution.Min(endTimeVar)); totalTime += solution.Min(endTimeVar); } @@ -105,8 +104,8 @@ public class VrpTimeWindows { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = new RoutingIndexManager( - data.TimeMatrix.GetLength(0), data.VehicleNumber, data.Depot); + RoutingIndexManager manager = + new RoutingIndexManager(data.TimeMatrix.GetLength(0), data.VehicleNumber, data.Depot); // [END index_manager] // Create Routing Model. @@ -116,13 +115,12 @@ public class VrpTimeWindows { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return data.TimeMatrix[fromNode, toNode]; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return data.TimeMatrix[fromNode, toNode]; + }); // [END transit_callback] // Define cost of each arc. @@ -141,24 +139,20 @@ public class VrpTimeWindows { // Add time window constraints for each location except depot. for (int i = 1; i < data.TimeWindows.GetLength(0); ++i) { long index = manager.NodeToIndex(i); - timeDimension.CumulVar(index).SetRange(data.TimeWindows[i, 0], - data.TimeWindows[i, 1]); + timeDimension.CumulVar(index).SetRange(data.TimeWindows[i, 0], data.TimeWindows[i, 1]); } // Add time window constraints for each vehicle start node. for (int i = 0; i < data.VehicleNumber; ++i) { long index = routing.Start(i); - timeDimension.CumulVar(index).SetRange(data.TimeWindows[0, 0], - data.TimeWindows[0, 1]); + timeDimension.CumulVar(index).SetRange(data.TimeWindows[0, 0], data.TimeWindows[0, 1]); } // [END time_constraint] // Instantiate route start and end times to produce feasible times. // [START depot_start_end_times] for (int i = 0; i < data.VehicleNumber; ++i) { - routing.AddVariableMinimizedByFinalizer( - timeDimension.CumulVar(routing.Start(i))); - routing.AddVariableMinimizedByFinalizer( - timeDimension.CumulVar(routing.End(i))); + routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.Start(i))); + routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.End(i))); } // [END depot_start_end_times] @@ -166,8 +160,7 @@ public class VrpTimeWindows { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. diff --git a/ortools/constraint_solver/samples/VrpWithTimeLimit.cs b/ortools/constraint_solver/samples/VrpWithTimeLimit.cs index 7fa40cf945..ef7ad0747f 100644 --- a/ortools/constraint_solver/samples/VrpWithTimeLimit.cs +++ b/ortools/constraint_solver/samples/VrpWithTimeLimit.cs @@ -27,8 +27,8 @@ public class Vrp { /// /// Print the solution. /// - static void PrintSolution(in RoutingIndexManager manager, - in RoutingModel routing, in Assignment solution) { + static void PrintSolution(in RoutingIndexManager manager, in RoutingModel routing, + in Assignment solution) { // Inspect solution. long maxRouteDistance = 0; for (int i = 0; i < manager.GetNumberOfVehicles(); ++i) { @@ -36,12 +36,12 @@ public class Vrp { long routeDistance = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { - Console.Write("{0} -> ", manager.IndexToNode((int) index)); + Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } - Console.WriteLine("{0}", manager.IndexToNode((int) index)); + Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); maxRouteDistance = Math.Max(routeDistance, maxRouteDistance); } @@ -59,8 +59,7 @@ public class Vrp { // Create Routing Index Manager // [START index_manager] - RoutingIndexManager manager = - new RoutingIndexManager(locationNumber, vehicleNumber, depot); + RoutingIndexManager manager = new RoutingIndexManager(locationNumber, vehicleNumber, depot); // [END index_manager] @@ -71,13 +70,12 @@ public class Vrp { // Create and register a transit callback. // [START transit_callback] - int transitCallbackIndex = - routing.RegisterTransitCallback((long fromIndex, long toIndex) => { - // Convert from routing variable Index to distance matrix NodeIndex. - var fromNode = manager.IndexToNode(fromIndex); - var toNode = manager.IndexToNode(toIndex); - return 1; - }); + int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => { + // Convert from routing variable Index to distance matrix NodeIndex. + var fromNode = manager.IndexToNode(fromIndex); + var toNode = manager.IndexToNode(toIndex); + return 1; + }); // [END transit_callback] // Define cost of each arc. @@ -91,8 +89,7 @@ public class Vrp { /*slack=*/0, /*horizon=*/3000, /*start_cumul_to_zero=*/true, "Distance"); - RoutingDimension distanceDimension = - routing.GetMutableDimension("Distance"); + RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // [END distance_constraint] @@ -100,12 +97,11 @@ public class Vrp { // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); - searchParameters.FirstSolutionStrategy = - FirstSolutionStrategy.Types.Value.PathCheapestArc; + searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch; searchParameters.LogSearch = true; - searchParameters.TimeLimit = new Duration{Seconds = 10}; + searchParameters.TimeLimit = new Duration { Seconds = 10 }; // [END parameters] // Solve the problem. diff --git a/ortools/dotnet/CreateSigningKey/Program.cs b/ortools/dotnet/CreateSigningKey/Program.cs index bf447afdec..c4acf8bd25 100644 --- a/ortools/dotnet/CreateSigningKey/Program.cs +++ b/ortools/dotnet/CreateSigningKey/Program.cs @@ -3,22 +3,23 @@ using System.IO; using System.Security.Cryptography; namespace CreateSigningKey { -class Program { - static void Main(string[] args) { - if (args == null || args.Length == 0) { - Console.WriteLine("Key filename not specified."); - return; + class Program { + static void Main(string[] args) { + if (args == null || args.Length == 0) { + Console.WriteLine("Key filename not specified."); + return; + } + string path = Directory.GetCurrentDirectory() + args[0]; + Console.WriteLine("Key filename:" + path); + if (Console.Out != null) + Console.Out.Flush(); + File.WriteAllBytes(path, GenerateStrongNameKeyPair()); } - string path = Directory.GetCurrentDirectory() + args[0]; - Console.WriteLine("Key filename:" + path); - if (Console.Out != null) Console.Out.Flush(); - File.WriteAllBytes(path, GenerateStrongNameKeyPair()); - } - public static byte[] GenerateStrongNameKeyPair() { - using(var provider = new RSACryptoServiceProvider(4096)) { - return provider.ExportCspBlob(!provider.PublicOnly); + public static byte[] GenerateStrongNameKeyPair() { + using (var provider = new RSACryptoServiceProvider(4096)) { + return provider.ExportCspBlob(!provider.PublicOnly); + } } } } -} diff --git a/ortools/graph/samples/SimpleMaxFlowProgram.cs b/ortools/graph/samples/SimpleMaxFlowProgram.cs index 8b5a58ef58..a4786ef21d 100644 --- a/ortools/graph/samples/SimpleMaxFlowProgram.cs +++ b/ortools/graph/samples/SimpleMaxFlowProgram.cs @@ -23,9 +23,9 @@ public class SimpleMaxFlowProgram { // capacity of 20. // From Taha's 'Introduction to Operations Research', // example 6.4-2. - int[] startNodes = {0, 0, 0, 1, 1, 2, 2, 3, 3}; - int[] endNodes = {1, 2, 3, 2, 4, 3, 4, 2, 4}; - int[] capacities = {20, 30, 10, 40, 30, 10, 20, 5, 20}; + int[] startNodes = { 0, 0, 0, 1, 1, 2, 2, 3, 3 }; + int[] endNodes = { 1, 2, 3, 2, 4, 3, 4, 2, 4 }; + int[] capacities = { 20, 30, 10, 40, 30, 10, 20, 5, 20 }; // [END data] // [START constraints] @@ -34,9 +34,9 @@ public class SimpleMaxFlowProgram { // Add each arc. for (int i = 0; i < startNodes.Length; ++i) { - int arc = - maxFlow.AddArcWithCapacity(startNodes[i], endNodes[i], capacities[i]); - if (arc != i) throw new Exception("Internal error"); + int arc = maxFlow.AddArcWithCapacity(startNodes[i], endNodes[i], capacities[i]); + if (arc != i) + throw new Exception("Internal error"); } // [END constraints] @@ -56,8 +56,7 @@ public class SimpleMaxFlowProgram { string.Format("{0,3}", maxFlow.Capacity(i))); } } else { - Console.WriteLine("Solving the max flow problem failed. Solver status: " + - solveStatus); + Console.WriteLine("Solving the max flow problem failed. Solver status: " + solveStatus); } // [END print_solution] } diff --git a/ortools/graph/samples/SimpleMinCostFlowProgram.cs b/ortools/graph/samples/SimpleMinCostFlowProgram.cs index 6112f74c0b..dcdd42cba0 100644 --- a/ortools/graph/samples/SimpleMinCostFlowProgram.cs +++ b/ortools/graph/samples/SimpleMinCostFlowProgram.cs @@ -23,13 +23,13 @@ public class SimpleMinCostFlowProgram { // costs between each pair. For instance, the arc from node 0 to node 1 has // a capacity of 15. Problem taken From Taha's 'Introduction to Operations // Research', example 6.4-2. - int[] startNodes = {0, 0, 1, 1, 1, 2, 2, 3, 4}; - int[] endNodes = {1, 2, 2, 3, 4, 3, 4, 4, 2}; - int[] capacities = {15, 8, 20, 4, 10, 15, 4, 20, 5}; - int[] unitCosts = {4, 4, 2, 2, 6, 1, 3, 2, 3}; + int[] startNodes = { 0, 0, 1, 1, 1, 2, 2, 3, 4 }; + int[] endNodes = { 1, 2, 2, 3, 4, 3, 4, 4, 2 }; + int[] capacities = { 15, 8, 20, 4, 10, 15, 4, 20, 5 }; + int[] unitCosts = { 4, 4, 2, 2, 6, 1, 3, 2, 3 }; // Define an array of supplies at each node. - int[] supplies = {20, 0, 0, -5, -15}; + int[] supplies = { 20, 0, 0, -5, -15 }; // [END data] // [START constraints] @@ -38,9 +38,10 @@ public class SimpleMinCostFlowProgram { // Add each arc. for (int i = 0; i < startNodes.Length; ++i) { - int arc = minCostFlow.AddArcWithCapacityAndUnitCost( - startNodes[i], endNodes[i], capacities[i], unitCosts[i]); - if (arc != i) throw new Exception("Internal error"); + int arc = minCostFlow.AddArcWithCapacityAndUnitCost(startNodes[i], endNodes[i], capacities[i], + unitCosts[i]); + if (arc != i) + throw new Exception("Internal error"); } // Add node supplies. @@ -62,16 +63,13 @@ public class SimpleMinCostFlowProgram { Console.WriteLine(" Edge Flow / Capacity Cost"); for (int i = 0; i < minCostFlow.NumArcs(); ++i) { long cost = minCostFlow.Flow(i) * minCostFlow.UnitCost(i); - Console.WriteLine(minCostFlow.Tail(i) + " -> " + minCostFlow.Head(i) + - " " + string.Format("{0,3}", minCostFlow.Flow(i)) + - " / " + - string.Format("{0,3}", minCostFlow.Capacity(i)) + - " " + string.Format("{0,3}", cost)); + Console.WriteLine(minCostFlow.Tail(i) + " -> " + minCostFlow.Head(i) + " " + + string.Format("{0,3}", minCostFlow.Flow(i)) + " / " + + string.Format("{0,3}", minCostFlow.Capacity(i)) + " " + + string.Format("{0,3}", cost)); } } else { - Console.WriteLine( - "Solving the min cost flow problem failed. Solver status: " + - solveStatus); + Console.WriteLine("Solving the min cost flow problem failed. Solver status: " + solveStatus); } // [END print_solution] } diff --git a/ortools/java/com/google/ortools/sat/CpModel.java b/ortools/java/com/google/ortools/sat/CpModel.java index ffb8817479..26c4a97a9d 100644 --- a/ortools/java/com/google/ortools/sat/CpModel.java +++ b/ortools/java/com/google/ortools/sat/CpModel.java @@ -1003,7 +1003,7 @@ public final class CpModel { return SatHelper.validateModel(model()); } - /** Write the model as a ascii protocol buffer to 'file'.*/ + /** Write the model as a ascii protocol buffer to 'file'. */ public Boolean exportToFile(String file) { return SatHelper.writeModelToFile(model(), file); } diff --git a/ortools/linear_solver/csharp/LinearConstraint.cs b/ortools/linear_solver/csharp/LinearConstraint.cs index 2b1ef45606..fbb9ee4388 100644 --- a/ortools/linear_solver/csharp/LinearConstraint.cs +++ b/ortools/linear_solver/csharp/LinearConstraint.cs @@ -16,9 +16,13 @@ namespace Google.OrTools.LinearSolver { using System.Collections.Generic; public class LinearConstraint { - public virtual String ToString() { return "LinearConstraint"; } + public virtual String ToString() { + return "LinearConstraint"; + } - public virtual Constraint Extract(Solver solver) { return null; } + public virtual Constraint Extract(Solver solver) { + return null; + } } public class RangeConstraint : LinearConstraint { @@ -33,8 +37,7 @@ namespace Google.OrTools.LinearSolver { } public override Constraint Extract(Solver solver) { - Dictionary coefficients = - new Dictionary(); + Dictionary coefficients = new Dictionary(); double constant = expr_.Visit(coefficients); Constraint ct = solver.MakeConstraint(lb_ - constant, ub_ - constant); foreach (KeyValuePair pair in coefficients) { @@ -43,7 +46,9 @@ namespace Google.OrTools.LinearSolver { return ct; } - public static implicit operator bool(RangeConstraint ct) { return false; } + public static implicit operator bool(RangeConstraint ct) { + return false; + } private LinearExpr expr_; private double lb_; @@ -62,8 +67,7 @@ namespace Google.OrTools.LinearSolver { } public override Constraint Extract(Solver solver) { - Dictionary coefficients = - new Dictionary(); + Dictionary coefficients = new Dictionary(); double constant = left_.Visit(coefficients); constant += right_.DoVisit(coefficients, -1); Constraint ct = solver.MakeConstraint(-constant, -constant); @@ -74,8 +78,7 @@ namespace Google.OrTools.LinearSolver { } public static implicit operator bool(Equality ct) { - return (object) ct.left_ == (object) ct.right_ ? ct.equality_ - : !ct.equality_; + return (object)ct.left_ == (object)ct.right_ ? ct.equality_ : !ct.equality_; } private LinearExpr left_; @@ -102,8 +105,7 @@ namespace Google.OrTools.LinearSolver { } public static implicit operator bool(VarEquality ct) { - return (object) ct.left_ == (object) ct.right_ ? ct.equality_ - : !ct.equality_; + return (object)ct.left_ == (object)ct.right_ ? ct.equality_ : !ct.equality_; } private Variable left_; @@ -112,12 +114,11 @@ namespace Google.OrTools.LinearSolver { } // TODO(user): Try to move this code back to the .swig with @define macros. - public partial class MPConstraintVector - : IDisposable, - System.Collections.IEnumerable + public partial class MPConstraintVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# MPConstraint array diff --git a/ortools/linear_solver/csharp/LinearExpr.cs b/ortools/linear_solver/csharp/LinearExpr.cs index 2fa24d6ad1..60e6815f4a 100644 --- a/ortools/linear_solver/csharp/LinearExpr.cs +++ b/ortools/linear_solver/csharp/LinearExpr.cs @@ -16,8 +16,7 @@ namespace Google.OrTools.LinearSolver { using System.Collections.Generic; public class LinearExpr { - public virtual double DoVisit(Dictionary coefficients, - double multiplier) { + public virtual double DoVisit(Dictionary coefficients, double multiplier) { return 0; } @@ -142,8 +141,7 @@ namespace Google.OrTools.LinearSolver { return "(" + expr_.ToString() + " * " + coeff_ + ")"; } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { double current_multiplier = multiplier * coeff_; if (current_multiplier != 0.0) { return expr_.DoVisit(coefficients, current_multiplier); @@ -166,8 +164,7 @@ namespace Google.OrTools.LinearSolver { return "(" + expr_.ToString() + " + " + coeff_ + ")"; } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { if (multiplier != 0.0) { return coeff_ * multiplier + expr_.DoVisit(coefficients, multiplier); } else { @@ -180,12 +177,15 @@ namespace Google.OrTools.LinearSolver { } class VarWrapper : LinearExpr { - public VarWrapper(Variable var) { this.var_ = var; } + public VarWrapper(Variable var) { + this.var_ = var; + } - public override String ToString() { return var_.Name(); } + public override String ToString() { + return var_.Name(); + } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { if (multiplier != 0.0) { if (coefficients.ContainsKey(var_)) { coefficients[var_] += multiplier; @@ -209,11 +209,9 @@ namespace Google.OrTools.LinearSolver { return "(" + left_.ToString() + " + " + right_.ToString() + ")"; } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { if (multiplier != 0.0) { - return left_.DoVisit(coefficients, multiplier) + - right_.DoVisit(coefficients, multiplier); + return left_.DoVisit(coefficients, multiplier) + right_.DoVisit(coefficients, multiplier); } else { return 0.0; } @@ -224,10 +222,11 @@ namespace Google.OrTools.LinearSolver { } public class SumArray : LinearExpr { - public SumArray(LinearExpr[] array) { this.array_ = array; } + public SumArray(LinearExpr[] array) { + this.array_ = array; + } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { if (multiplier != 0.0) { double constant = 0.0; foreach (LinearExpr expr in array_) { @@ -243,10 +242,11 @@ namespace Google.OrTools.LinearSolver { } public class SumVarArray : LinearExpr { - public SumVarArray(Variable[] array) { this.array_ = array; } + public SumVarArray(Variable[] array) { + this.array_ = array; + } - public override double DoVisit(Dictionary coefficients, - double multiplier) { + public override double DoVisit(Dictionary coefficients, double multiplier) { if (multiplier != 0.0) { foreach (Variable var in array_) { if (coefficients.ContainsKey(var)) { diff --git a/ortools/linear_solver/csharp/SolverHelper.cs b/ortools/linear_solver/csharp/SolverHelper.cs index 33db31d89b..0f0a1fabba 100644 --- a/ortools/linear_solver/csharp/SolverHelper.cs +++ b/ortools/linear_solver/csharp/SolverHelper.cs @@ -20,46 +20,39 @@ namespace Google.OrTools.LinearSolver { // - customize the construction, and the OptimizationProblemType enum. // - support the natural language API. public partial class Solver { - public Variable[] MakeVarArray(int count, double lb, double ub, - bool integer) { + public Variable[] MakeVarArray(int count, double lb, double ub, bool integer) { Variable[] array = new Variable[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeVar(lb, ub, integer, ""); + array[i] = MakeVar(lb, ub, integer, ""); } return array; } - public Variable[] MakeVarArray(int count, double lb, double ub, - bool integer, string var_name) { + public Variable[] MakeVarArray(int count, double lb, double ub, bool integer, string var_name) { Variable[] array = new Variable[count]; for (int i = 0; i < count; ++i) { - array [i] - = MakeVar(lb, ub, integer, var_name + i); + array[i] = MakeVar(lb, ub, integer, var_name + i); } return array; } - public Variable[, ] MakeVarMatrix(int rows, int cols, double lb, double ub, - bool integer) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeVarMatrix(int rows, int cols, double lb, double ub, bool integer) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - matrix [i, j] - = MakeVar(lb, ub, integer, ""); + matrix[i, j] = MakeVar(lb, ub, integer, ""); } } return matrix; } - public Variable[, ] MakeVarMatrix(int rows, int cols, double lb, double ub, - bool integer, string name) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeVarMatrix(int rows, int cols, double lb, double ub, bool integer, + string name) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - matrix [i, j] - = MakeVar(lb, ub, integer, var_name); + matrix[i, j] = MakeVar(lb, ub, integer, var_name); } } return matrix; @@ -69,31 +62,26 @@ namespace Google.OrTools.LinearSolver { return MakeVarArray(count, lb, ub, false); } - public Variable[] MakeNumVarArray(int count, double lb, double ub, - string var_name) { + public Variable[] MakeNumVarArray(int count, double lb, double ub, string var_name) { return MakeVarArray(count, lb, ub, false, var_name); } - public Variable[, ] MakeNumVarMatrix(int rows, int cols, double lb, - double ub) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeNumVarMatrix(int rows, int cols, double lb, double ub) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - matrix [i, j] - = MakeNumVar(lb, ub, ""); + matrix[i, j] = MakeNumVar(lb, ub, ""); } } return matrix; } - public Variable[, ] MakeNumVarMatrix(int rows, int cols, double lb, - double ub, string name) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeNumVarMatrix(int rows, int cols, double lb, double ub, string name) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - matrix [i, j] - = MakeNumVar(lb, ub, var_name); + matrix[i, j] = MakeNumVar(lb, ub, var_name); } } return matrix; @@ -103,31 +91,26 @@ namespace Google.OrTools.LinearSolver { return MakeVarArray(count, lb, ub, true); } - public Variable[] MakeIntVarArray(int count, double lb, double ub, - string var_name) { + public Variable[] MakeIntVarArray(int count, double lb, double ub, string var_name) { return MakeVarArray(count, lb, ub, true, var_name); } - public Variable[, ] MakeIntVarMatrix(int rows, int cols, double lb, - double ub) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeIntVarMatrix(int rows, int cols, double lb, double ub) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - matrix [i, j] - = MakeIntVar(lb, ub, ""); + matrix[i, j] = MakeIntVar(lb, ub, ""); } } return matrix; } - public Variable[, ] MakeIntVarMatrix(int rows, int cols, double lb, - double ub, string name) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeIntVarMatrix(int rows, int cols, double lb, double ub, string name) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - matrix [i, j] - = MakeIntVar(lb, ub, var_name); + matrix[i, j] = MakeIntVar(lb, ub, var_name); } } return matrix; @@ -141,24 +124,22 @@ namespace Google.OrTools.LinearSolver { return MakeVarArray(count, 0.0, 1.0, true, var_name); } - public Variable[, ] MakeBoolVarMatrix(int rows, int cols) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeBoolVarMatrix(int rows, int cols) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { - matrix [i, j] - = MakeBoolVar(""); + matrix[i, j] = MakeBoolVar(""); } } return matrix; } - public Variable[, ] MakeBoolVarMatrix(int rows, int cols, string name) { - Variable[, ] matrix = new Variable[rows, cols]; + public Variable[,] MakeBoolVarMatrix(int rows, int cols, string name) { + Variable[,] matrix = new Variable[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; - matrix [i, j] - = MakeBoolVar(var_name); + matrix[i, j] = MakeBoolVar(var_name); } } return matrix; @@ -171,8 +152,7 @@ namespace Google.OrTools.LinearSolver { public void Minimize(LinearExpr expr) { Objective().Clear(); Objective().SetMinimization(); - Dictionary coefficients = - new Dictionary(); + Dictionary coefficients = new Dictionary(); double constant = expr.Visit(coefficients); foreach (KeyValuePair pair in coefficients) { Objective().SetCoefficient(pair.Key, pair.Value); @@ -183,8 +163,7 @@ namespace Google.OrTools.LinearSolver { public void Maximize(LinearExpr expr) { Objective().Clear(); Objective().SetMaximization(); - Dictionary coefficients = - new Dictionary(); + Dictionary coefficients = new Dictionary(); double constant = expr.Visit(coefficients); foreach (KeyValuePair pair in coefficients) { Objective().SetCoefficient(pair.Key, pair.Value); diff --git a/ortools/linear_solver/csharp/VariableHelper.cs b/ortools/linear_solver/csharp/VariableHelper.cs index dd01d313bd..85dba02a95 100644 --- a/ortools/linear_solver/csharp/VariableHelper.cs +++ b/ortools/linear_solver/csharp/VariableHelper.cs @@ -21,7 +21,9 @@ namespace Google.OrTools.LinearSolver { return new VarWrapper(a) + v; } - public static LinearExpr operator +(double v, Variable a) { return a + v; } + public static LinearExpr operator +(double v, Variable a) { + return a + v; + } public static LinearExpr operator +(Variable a, LinearExpr b) { return new VarWrapper(a) + b; @@ -153,12 +155,11 @@ namespace Google.OrTools.LinearSolver { } // TODO(user): Try to move this code back to the .swig with @define macros. - public partial class MPVariableVector - : IDisposable, - System.Collections.IEnumerable + public partial class MPVariableVector : IDisposable, + System.Collections.IEnumerable #if !SWIG_DOTNET_1 , - System.Collections.Generic.IList + System.Collections.Generic.IList #endif { // cast from C# MPVariable array diff --git a/ortools/linear_solver/samples/AssignmentMip.cs b/ortools/linear_solver/samples/AssignmentMip.cs index 4be661eb9c..36100a8086 100644 --- a/ortools/linear_solver/samples/AssignmentMip.cs +++ b/ortools/linear_solver/samples/AssignmentMip.cs @@ -21,9 +21,9 @@ public class AssignmentMip { static void Main() { // Data. // [START data_model] - int[, ] costs = { - {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, - {45, 110, 95, 115}, {50, 100, 90, 100}, + int[,] costs = { + { 90, 80, 75, 70 }, { 35, 85, 55, 65 }, { 125, 95, 90, 95 }, + { 45, 110, 95, 115 }, { 50, 100, 90, 100 }, }; int numWorkers = costs.GetLength(0); int numTasks = costs.GetLength(1); @@ -38,7 +38,7 @@ public class AssignmentMip { // [START variables] // x[i, j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. - Variable[, ] x = new Variable[numWorkers, numTasks]; + Variable[,] x = new Variable[numWorkers, numTasks]; for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { x[i, j] = solver.MakeIntVar(0, 1, $"worker_{i}_task_{j}"); @@ -90,10 +90,8 @@ public class AssignmentMip { for (int j = 0; j < numTasks; ++j) { // Test if x[i, j] is 0 or 1 (with tolerance for floating point // arithmetic). - if (x [i, j] - .SolutionValue() > 0.5) { - Console.WriteLine( - $"Worker {i} assigned to task {j}. Cost: {costs[i, j]}"); + if (x[i, j].SolutionValue() > 0.5) { + Console.WriteLine($"Worker {i} assigned to task {j}. Cost: {costs[i, j]}"); } } } diff --git a/ortools/linear_solver/samples/BinPackingMip.cs b/ortools/linear_solver/samples/BinPackingMip.cs index 016a7c8bd9..1819ef3759 100644 --- a/ortools/linear_solver/samples/BinPackingMip.cs +++ b/ortools/linear_solver/samples/BinPackingMip.cs @@ -21,8 +21,7 @@ using Google.OrTools.LinearSolver; public class BinPackingMip { // [START data_model] class DataModel { - public static double[] Weights = {48, 30, 19, 36, 36, 27, - 42, 42, 36, 24, 30}; + public static double[] Weights = { 48, 30, 19, 36, 36, 27, 42, 42, 36, 24, 30 }; public int NumItems = Weights.Length; public int NumBins = Weights.Length; public double BinCapacity = 100.0; @@ -41,7 +40,7 @@ public class BinPackingMip { // [START program_part2] // [START variables] - Variable[, ] x = new Variable[data.NumItems, data.NumBins]; + Variable[,] x = new Variable[data.NumItems, data.NumBins]; for (int i = 0; i < data.NumItems; i++) { for (int j = 0; j < data.NumBins; j++) { x[i, j] = solver.MakeIntVar(0, 1, $"x_{i}_{j}"); @@ -62,8 +61,7 @@ public class BinPackingMip { } for (int j = 0; j < data.NumBins; ++j) { - Constraint constraint = - solver.MakeConstraint(0, Double.PositiveInfinity, ""); + Constraint constraint = solver.MakeConstraint(0, Double.PositiveInfinity, ""); constraint.SetCoefficient(y[j], data.BinCapacity); for (int i = 0; i < data.NumItems; ++i) { constraint.SetCoefficient(x[i, j], -DataModel.Weights[i]); @@ -93,12 +91,10 @@ public class BinPackingMip { double TotalWeight = 0.0; for (int j = 0; j < data.NumBins; ++j) { double BinWeight = 0.0; - if (y [j] - .SolutionValue() == 1) { + if (y[j].SolutionValue() == 1) { Console.WriteLine($"Bin {j}"); for (int i = 0; i < data.NumItems; ++i) { - if (x [i, j] - .SolutionValue() == 1) { + if (x[i, j].SolutionValue() == 1) { Console.WriteLine($"Item {i} weight: {DataModel.Weights[i]}"); BinWeight += DataModel.Weights[i]; } diff --git a/ortools/linear_solver/samples/LinearProgrammingExample.cs b/ortools/linear_solver/samples/LinearProgrammingExample.cs index 3ce2b9e4c8..ab09be5699 100644 --- a/ortools/linear_solver/samples/LinearProgrammingExample.cs +++ b/ortools/linear_solver/samples/LinearProgrammingExample.cs @@ -63,8 +63,7 @@ public class LinearProgrammingExample { Console.WriteLine("x = " + x.SolutionValue()); Console.WriteLine("y = " + y.SolutionValue()); // The objective value of the solution. - Console.WriteLine("Optimal objective value = " + - solver.Objective().Value()); + Console.WriteLine("Optimal objective value = " + solver.Objective().Value()); // [END print_solution] } } diff --git a/ortools/linear_solver/samples/MipVarArray.cs b/ortools/linear_solver/samples/MipVarArray.cs index 96bb4e3ec2..308db13a62 100644 --- a/ortools/linear_solver/samples/MipVarArray.cs +++ b/ortools/linear_solver/samples/MipVarArray.cs @@ -21,14 +21,14 @@ using Google.OrTools.LinearSolver; public class MipVarArray { // [START data_model] class DataModel { - public double[, ] ConstraintCoeffs = { - {5, 7, 9, 2, 1}, - {18, 4, -9, 10, 12}, - {4, 7, 3, 8, 5}, - {5, 13, 16, 3, -7}, + public double[,] ConstraintCoeffs = { + { 5, 7, 9, 2, 1 }, + { 18, 4, -9, 10, 12 }, + { 4, 7, 3, 8, 5 }, + { 5, 13, 16, 3, -7 }, }; - public double[] Bounds = {250, 285, 211, 315}; - public double[] ObjCoeffs = {7, 8, 2, 9, 6}; + public double[] Bounds = { 250, 285, 211, 315 }; + public double[] ObjCoeffs = { 7, 8, 2, 9, 6 }; public int NumVars = 5; public int NumConstraints = 4; } @@ -83,24 +83,18 @@ public class MipVarArray { } Console.WriteLine("Solution:"); - Console.WriteLine("Optimal objective value = " + - solver.Objective().Value()); + Console.WriteLine("Optimal objective value = " + solver.Objective().Value()); for (int j = 0; j < data.NumVars; ++j) { - Console.WriteLine("x[" + j + "] = " + - x [j] - .SolutionValue()); + Console.WriteLine("x[" + j + "] = " + x[j].SolutionValue()); } // [END print_solution] // [START advanced] Console.WriteLine("\nAdvanced usage:"); - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); - Console.WriteLine("Problem solved in " + solver.Iterations() + - " iterations"); - Console.WriteLine("Problem solved in " + solver.Nodes() + - " branch-and-bound nodes"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); + Console.WriteLine("Problem solved in " + solver.Iterations() + " iterations"); + Console.WriteLine("Problem solved in " + solver.Nodes() + " branch-and-bound nodes"); // [END advanced] } } diff --git a/ortools/linear_solver/samples/MultipleKnapsackMip.cs b/ortools/linear_solver/samples/MultipleKnapsackMip.cs index 5d43edfda7..14efed5846 100644 --- a/ortools/linear_solver/samples/MultipleKnapsackMip.cs +++ b/ortools/linear_solver/samples/MultipleKnapsackMip.cs @@ -21,11 +21,9 @@ using Google.OrTools.LinearSolver; public class MultipleKnapsackMip { // [START data_model] class DataModel { - public static double[] Weights = {48, 30, 42, 36, 36, 48, 42, 42, - 36, 24, 30, 30, 42, 36, 36}; - public static double[] Values = {10, 30, 25, 50, 35, 30, 15, 40, - 30, 35, 45, 10, 20, 30, 25}; - public double[] BinCapacities = {100, 100, 100, 100, 100}; + public static double[] Weights = { 48, 30, 42, 36, 36, 48, 42, 42, 36, 24, 30, 30, 42, 36, 36 }; + public static double[] Values = { 10, 30, 25, 50, 35, 30, 15, 40, 30, 35, 45, 10, 20, 30, 25 }; + public double[] BinCapacities = { 100, 100, 100, 100, 100 }; public int NumItems = Weights.Length; public int NumBins = 5; } @@ -43,7 +41,7 @@ public class MultipleKnapsackMip { // [START program_part2] // [START variables] - Variable[, ] x = new Variable[data.NumItems, data.NumBins]; + Variable[,] x = new Variable[data.NumItems, data.NumBins]; for (int i = 0; i < data.NumItems; i++) { for (int j = 0; j < data.NumBins; j++) { x[i, j] = solver.MakeIntVar(0, 1, $"x_{i}_{j}"); @@ -60,8 +58,7 @@ public class MultipleKnapsackMip { } for (int j = 0; j < data.NumBins; ++j) { - Constraint constraint = - solver.MakeConstraint(0, data.BinCapacities[j], ""); + Constraint constraint = solver.MakeConstraint(0, data.BinCapacities[j], ""); for (int i = 0; i < data.NumItems; ++i) { constraint.SetCoefficient(x[i, j], DataModel.Weights[i]); } @@ -95,8 +92,7 @@ public class MultipleKnapsackMip { double BinValue = 0.0; Console.WriteLine("Bin " + j); for (int i = 0; i < data.NumItems; ++i) { - if (x [i, j] - .SolutionValue() == 1) { + if (x[i, j].SolutionValue() == 1) { Console.WriteLine( $"Item {i} weight: {DataModel.Weights[i]} values: {DataModel.Values[i]}"); BinWeight += DataModel.Weights[i]; diff --git a/ortools/linear_solver/samples/SimpleMipProgram.cs b/ortools/linear_solver/samples/SimpleMipProgram.cs index e0bff1a12e..3f11084bf1 100644 --- a/ortools/linear_solver/samples/SimpleMipProgram.cs +++ b/ortools/linear_solver/samples/SimpleMipProgram.cs @@ -65,12 +65,9 @@ public class SimpleMipProgram { // [START advanced] Console.WriteLine("\nAdvanced usage:"); - Console.WriteLine("Problem solved in " + solver.WallTime() + - " milliseconds"); - Console.WriteLine("Problem solved in " + solver.Iterations() + - " iterations"); - Console.WriteLine("Problem solved in " + solver.Nodes() + - " branch-and-bound nodes"); + Console.WriteLine("Problem solved in " + solver.WallTime() + " milliseconds"); + Console.WriteLine("Problem solved in " + solver.Iterations() + " iterations"); + Console.WriteLine("Problem solved in " + solver.Nodes() + " branch-and-bound nodes"); // [END advanced] } } diff --git a/ortools/sat/csharp/CpModel.cs b/ortools/sat/csharp/CpModel.cs index 767d3ad757..6ad67936b4 100644 --- a/ortools/sat/csharp/CpModel.cs +++ b/ortools/sat/csharp/CpModel.cs @@ -31,7 +31,9 @@ namespace Google.OrTools.Sat { get { return model_; } } - int Negated(int index) { return -index - 1; } + int Negated(int index) { + return -index - 1; + } // Integer variables and constraints. @@ -57,13 +59,11 @@ namespace Google.OrTools.Sat { return new IntVar(model_, new Domain(0, 1), name); } - public Constraint AddLinearConstraint(LinearExpr linear_expr, long lb, - long ub) { + public Constraint AddLinearConstraint(LinearExpr linear_expr, long lb, long ub) { return AddLinearExpressionInDomain(linear_expr, new Domain(lb, ub)); } - public Constraint AddLinearExpressionInDomain(LinearExpr linear_expr, - Domain domain) { + public Constraint AddLinearExpressionInDomain(LinearExpr linear_expr, Domain domain) { Dictionary dict = new Dictionary(); long constant = LinearExpr.GetVarValueMap(linear_expr, 1L, dict); Constraint ct = new Constraint(model_); @@ -86,28 +86,23 @@ namespace Google.OrTools.Sat { public Constraint Add(BoundedLinearExpression lin) { switch (lin.CtType) { case BoundedLinearExpression.Type.BoundExpression: { - return AddLinearExpressionInDomain(lin.Left, - new Domain(lin.Lb, lin.Ub)); + return AddLinearExpressionInDomain(lin.Left, new Domain(lin.Lb, lin.Ub)); } case BoundedLinearExpression.Type.VarEqVar: { - return AddLinearExpressionInDomain(lin.Left - lin.Right, - new Domain(0)); + return AddLinearExpressionInDomain(lin.Left - lin.Right, new Domain(0)); } case BoundedLinearExpression.Type.VarDiffVar: { return AddLinearExpressionInDomain( lin.Left - lin.Right, - Domain.FromFlatIntervals( - new long[]{Int64.MinValue, -1, 1, Int64.MaxValue})); + Domain.FromFlatIntervals(new long[] { Int64.MinValue, -1, 1, Int64.MaxValue })); } case BoundedLinearExpression.Type.VarEqCst: { - return AddLinearExpressionInDomain(lin.Left, - new Domain(lin.Lb, lin.Lb)); + return AddLinearExpressionInDomain(lin.Left, new Domain(lin.Lb, lin.Lb)); } case BoundedLinearExpression.Type.VarDiffCst: { return AddLinearExpressionInDomain( - lin.Left, - Domain.FromFlatIntervals(new long[]{Int64.MinValue, lin.Lb - 1, - lin.Lb + 1, Int64.MaxValue})); + lin.Left, Domain.FromFlatIntervals( + new long[] { Int64.MinValue, lin.Lb - 1, lin.Lb + 1, Int64.MaxValue })); } } return null; @@ -123,8 +118,7 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddElement(IntVar index, IEnumerable vars, - IntVar target) { + public Constraint AddElement(IntVar index, IEnumerable vars, IntVar target) { Constraint ct = new Constraint(model_); ElementConstraintProto element = new ElementConstraintProto(); element.Index = index.Index; @@ -136,8 +130,7 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddElement(IntVar index, IEnumerable values, - IntVar target) { + public Constraint AddElement(IntVar index, IEnumerable values, IntVar target) { Constraint ct = new Constraint(model_); ElementConstraintProto element = new ElementConstraintProto(); element.Index = index.Index; @@ -149,8 +142,7 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddElement(IntVar index, IEnumerable values, - IntVar target) { + public Constraint AddElement(IntVar index, IEnumerable values, IntVar target) { Constraint ct = new Constraint(model_); ElementConstraintProto element = new ElementConstraintProto(); element.Index = index.Index; @@ -174,8 +166,7 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddAllowedAssignments(IEnumerable vars, - long[, ] tuples) { + public Constraint AddAllowedAssignments(IEnumerable vars, long[,] tuples) { Constraint ct = new Constraint(model_); TableConstraintProto table = new TableConstraintProto(); foreach (IntVar var in vars) { @@ -190,16 +181,14 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddForbiddenAssignments(IEnumerable vars, - long[, ] tuples) { + public Constraint AddForbiddenAssignments(IEnumerable vars, long[,] tuples) { Constraint ct = AddAllowedAssignments(vars, tuples); ct.Proto.Table.Negated = true; return ct; } - public Constraint AddAutomaton(IEnumerable vars, - long starting_state, long[, ] transitions, - IEnumerable final_states) { + public Constraint AddAutomaton(IEnumerable vars, long starting_state, + long[,] transitions, IEnumerable final_states) { Constraint ct = new Constraint(model_); AutomatonConstraintProto aut = new AutomatonConstraintProto(); foreach (IntVar var in vars) { @@ -219,10 +208,9 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddAutomaton( - IEnumerable vars, long starting_state, - IEnumerable> transitions, - IEnumerable final_states) { + public Constraint AddAutomaton(IEnumerable vars, long starting_state, + IEnumerable> transitions, + IEnumerable final_states) { Constraint ct = new Constraint(model_); AutomatonConstraintProto aut = new AutomatonConstraintProto(); foreach (IntVar var in vars) { @@ -242,8 +230,7 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddInverse(IEnumerable direct, - IEnumerable reverse) { + public Constraint AddInverse(IEnumerable direct, IEnumerable reverse) { Constraint ct = new Constraint(model_); InverseConstraintProto inverse = new InverseConstraintProto(); foreach (IntVar var in direct) { @@ -256,10 +243,8 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddReservoirConstraint(IEnumerable times, - IEnumerable demands, - long min_level, - long max_level) { + public Constraint AddReservoirConstraint(IEnumerable times, IEnumerable demands, + long min_level, long max_level) { Constraint ct = new Constraint(model_); ReservoirConstraintProto res = new ReservoirConstraintProto(); foreach (IntVar var in times) { @@ -276,9 +261,10 @@ namespace Google.OrTools.Sat { return ct; } - public Constraint AddReservoirConstraintWithActive( - IEnumerable times, IEnumerable demands, - IEnumerable actives, long min_level, long max_level) { + public Constraint AddReservoirConstraintWithActive(IEnumerable times, + IEnumerable demands, + IEnumerable actives, + long min_level, long max_level) { Constraint ct = new Constraint(model_); ReservoirConstraintProto res = new ReservoirConstraintProto(); foreach (IntVar var in times) { @@ -297,8 +283,7 @@ namespace Google.OrTools.Sat { return ct; } - public void AddMapDomain(IntVar var, IEnumerable bool_vars, - long offset = 0) { + public void AddMapDomain(IntVar var, IEnumerable bool_vars, long offset = 0) { int i = 0; foreach (IntVar bool_var in bool_vars) { int b_index = bool_var.Index; @@ -434,21 +419,16 @@ namespace Google.OrTools.Sat { // Scheduling support - public IntervalVar NewIntervalVar(S start, D duration, E end, - string name) { - return new IntervalVar(model_, GetOrCreateIndex(start), - GetOrCreateIndex(duration), GetOrCreateIndex(end), - name); + public IntervalVar NewIntervalVar(S start, D duration, E end, string name) { + return new IntervalVar(model_, GetOrCreateIndex(start), GetOrCreateIndex(duration), + GetOrCreateIndex(end), name); } - public IntervalVar NewOptionalIntervalVar(S start, D duration, - E end, - ILiteral is_present, - string name) { + public IntervalVar NewOptionalIntervalVar(S start, D duration, E end, + ILiteral is_present, string name) { int i = is_present.GetIndex(); - return new IntervalVar(model_, GetOrCreateIndex(start), - GetOrCreateIndex(duration), GetOrCreateIndex(end), - i, name); + return new IntervalVar(model_, GetOrCreateIndex(start), GetOrCreateIndex(duration), + GetOrCreateIndex(end), i, name); } public Constraint AddNoOverlap(IEnumerable intervals) { @@ -491,35 +471,45 @@ namespace Google.OrTools.Sat { } // Objective. - public void Minimize(LinearExpr obj) { SetObjective(obj, true); } + public void Minimize(LinearExpr obj) { + SetObjective(obj, true); + } - public void Maximize(LinearExpr obj) { SetObjective(obj, false); } + public void Maximize(LinearExpr obj) { + SetObjective(obj, false); + } - public void Minimize() { SetObjective(null, true); } + public void Minimize() { + SetObjective(null, true); + } - public void Maximize() { SetObjective(null, false); } + public void Maximize() { + SetObjective(null, false); + } public void AddVarToObjective(IntVar var) { - if ((Object) var == null) return; + if ((Object)var == null) + return; model_.Objective.Vars.Add(var.Index); model_.Objective.Coeffs.Add(model_.Objective.ScalingFactor > 0 ? 1 : -1); } public void AddTermToObjective(IntVar var, long coeff) { - if (coeff == 0 || (Object) var == null) return; + if (coeff == 0 || (Object)var == null) + return; model_.Objective.Vars.Add(var.Index); - model_.Objective.Coeffs.Add(model_.Objective.ScalingFactor > 0 ? coeff - : -coeff); + model_.Objective.Coeffs.Add(model_.Objective.ScalingFactor > 0 ? coeff : -coeff); } - bool HasObjective() { return model_.Objective == null; } + bool HasObjective() { + return model_.Objective == null; + } // Search Decision. - public void AddDecisionStrategy( - IEnumerable vars, - DecisionStrategyProto.Types.VariableSelectionStrategy var_str, - DecisionStrategyProto.Types.DomainReductionStrategy dom_str) { + public void AddDecisionStrategy(IEnumerable vars, + DecisionStrategyProto.Types.VariableSelectionStrategy var_str, + DecisionStrategyProto.Types.DomainReductionStrategy dom_str) { DecisionStrategyProto ds = new DecisionStrategyProto(); foreach (IntVar var in vars) { ds.Variables.Add(var.Index); @@ -572,13 +562,17 @@ namespace Google.OrTools.Sat { model_.Objective = objective; } - public String ModelStats() { return SatHelper.ModelStats(model_); } + public String ModelStats() { + return SatHelper.ModelStats(model_); + } public Boolean ExportToFile(String filename) { return SatHelper.WriteModelToFile(model_, filename); } - public String Validate() { return SatHelper.ValidateModel(model_); } + public String Validate() { + return SatHelper.ValidateModel(model_); + } private int ConvertConstant(long value) { if (constant_map_.ContainsKey(value)) { @@ -596,7 +590,7 @@ namespace Google.OrTools.Sat { private int GetOrCreateIndex(X x) { if (typeof(X) == typeof(IntVar)) { - IntVar vx = (IntVar)(Object) x; + IntVar vx = (IntVar)(Object)x; return vx.Index; } if (typeof(X) == typeof(long) || typeof(X) == typeof(int)) { diff --git a/ortools/sat/csharp/CpSolver.cs b/ortools/sat/csharp/CpSolver.cs index d323cba189..d55c9960cc 100644 --- a/ortools/sat/csharp/CpSolver.cs +++ b/ortools/sat/csharp/CpSolver.cs @@ -18,36 +18,32 @@ namespace Google.OrTools.Sat { public class CpSolver { public CpSolverStatus Solve(CpModel model) { if (string_parameters_ != null) { - response_ = SatHelper.SolveWithStringParameters(model.Model, - string_parameters_); + response_ = SatHelper.SolveWithStringParameters(model.Model, string_parameters_); } else { response_ = SatHelper.Solve(model.Model); } return response_.Status; } - public CpSolverStatus SolveWithSolutionCallback(CpModel model, - SolutionCallback cb) { + public CpSolverStatus SolveWithSolutionCallback(CpModel model, SolutionCallback cb) { if (string_parameters_ != null) { - response_ = SatHelper.SolveWithStringParametersAndSolutionCallback( - model.Model, string_parameters_, cb); + response_ = SatHelper.SolveWithStringParametersAndSolutionCallback(model.Model, + string_parameters_, cb); } else { - response_ = SatHelper.SolveWithStringParametersAndSolutionCallback( - model.Model, "", cb); + response_ = SatHelper.SolveWithStringParametersAndSolutionCallback(model.Model, "", cb); } return response_.Status; } - public CpSolverStatus SearchAllSolutions(CpModel model, - SolutionCallback cb) { + public CpSolverStatus SearchAllSolutions(CpModel model, SolutionCallback cb) { if (string_parameters_ != null) { string extra_parameters = " enumerate_all_solutions:true"; response_ = SatHelper.SolveWithStringParametersAndSolutionCallback( model.Model, string_parameters_ + extra_parameters, cb); } else { string parameters = "enumerate_all_solutions:true"; - response_ = SatHelper.SolveWithStringParametersAndSolutionCallback( - model.Model, parameters, cb); + response_ = + SatHelper.SolveWithStringParametersAndSolutionCallback(model.Model, parameters, cb); } return response_.Status; } @@ -85,16 +81,17 @@ namespace Google.OrTools.Sat { exprs.RemoveAt(0); long coeff = coeffs[0]; coeffs.RemoveAt(0); - if (coeff == 0) continue; + if (coeff == 0) + continue; if (expr is ProductCst) { - ProductCst p = (ProductCst) expr; + ProductCst p = (ProductCst)expr; if (p.Coeff != 0) { exprs.Add(p.Expr); coeffs.Add(p.Coeff * coeff); } } else if (expr is SumArray) { - SumArray a = (SumArray) expr; + SumArray a = (SumArray)expr; constant += coeff * a.Constant; foreach (LinearExpr sub in a.Expressions) { exprs.Add(sub); @@ -102,12 +99,10 @@ namespace Google.OrTools.Sat { } } else if (expr is IntVar) { int index = expr.Index; - long value = index >= 0 ? response_.Solution[index] - : -response_.Solution[-index - 1]; + long value = index >= 0 ? response_.Solution[index] : -response_.Solution[-index - 1]; constant += coeff * value; } else if (expr is NotBooleanVariable) { - throw new ArgumentException( - "Cannot evaluate a literal in an integer expression."); + throw new ArgumentException("Cannot evaluate a literal in an integer expression."); } else { throw new ArgumentException("Cannot evaluate '" + expr.ToString() + "' in an integer expression"); @@ -130,11 +125,17 @@ namespace Google.OrTools.Sat { } } - public long NumBranches() { return response_.NumBranches; } + public long NumBranches() { + return response_.NumBranches; + } - public long NumConflicts() { return response_.NumConflicts; } + public long NumConflicts() { + return response_.NumConflicts; + } - public double WallTime() { return response_.WallTime; } + public double WallTime() { + return response_.WallTime; + } private CpModelProto model_; private CpSolverResponse response_; diff --git a/ortools/sat/csharp/IntegerExpressions.cs b/ortools/sat/csharp/IntegerExpressions.cs index 1fabd2134e..3ae90cd27d 100644 --- a/ortools/sat/csharp/IntegerExpressions.cs +++ b/ortools/sat/csharp/IntegerExpressions.cs @@ -20,18 +20,15 @@ namespace Google.OrTools.Sat { // IntVar[] helper class. public static class IntVarArrayHelper { - [Obsolete( - "This Sum method is deprecated, please use LinearExpr.Sum() instead.")] + [Obsolete("This Sum method is deprecated, please use LinearExpr.Sum() instead.")] public static LinearExpr Sum(this IntVar[] vars) { return LinearExpr.Sum(vars); } - [Obsolete( - "This ScalProd method is deprecated, please use LinearExpr.ScalProd() instead.")] + [Obsolete("This ScalProd method is deprecated, please use LinearExpr.ScalProd() instead.")] public static LinearExpr ScalProd(this IntVar[] vars, int[] coeffs) { return LinearExpr.ScalProd(vars, coeffs); } - [Obsolete( - "This ScalProd method is deprecated, please use LinearExpr.ScalProd() instead.")] + [Obsolete("This ScalProd method is deprecated, please use LinearExpr.ScalProd() instead.")] public static LinearExpr ScalProd(this IntVar[] vars, long[] coeffs) { return LinearExpr.ScalProd(vars, coeffs); } @@ -52,13 +49,11 @@ namespace Google.OrTools.Sat { return new SumArray(exprs); } - public static LinearExpr ScalProd(IEnumerable vars, - IEnumerable coeffs) { + public static LinearExpr ScalProd(IEnumerable vars, IEnumerable coeffs) { return new SumArray(vars, coeffs); } - public static LinearExpr ScalProd(IEnumerable vars, - IEnumerable coeffs) { + public static LinearExpr ScalProd(IEnumerable vars, IEnumerable coeffs) { return new SumArray(vars, coeffs); } @@ -70,9 +65,13 @@ namespace Google.OrTools.Sat { get { return GetIndex(); } } - public virtual int GetIndex() { throw new NotImplementedException(); } + public virtual int GetIndex() { + throw new NotImplementedException(); + } - public virtual string ShortString() { return ToString(); } + public virtual string ShortString() { + return ToString(); + } public static LinearExpr operator +(LinearExpr a, LinearExpr b) { return new SumArray(a, b); @@ -106,15 +105,15 @@ namespace Google.OrTools.Sat { return Prod(a, v); } - public static LinearExpr operator -(LinearExpr a) { return Prod(a, -1); } + public static LinearExpr operator -(LinearExpr a) { + return Prod(a, -1); + } - public static BoundedLinearExpression operator ==(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator ==(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(a, b, true); } - public static BoundedLinearExpression operator !=(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator !=(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(a, b, false); } @@ -158,23 +157,19 @@ namespace Google.OrTools.Sat { return a > v; } - public static BoundedLinearExpression operator >=(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator >=(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(0, a - b, Int64.MaxValue); } - public static BoundedLinearExpression operator>(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator>(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(1, a - b, Int64.MaxValue); } - public static BoundedLinearExpression operator <=(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator <=(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(Int64.MinValue, a - b, 0); } - public static BoundedLinearExpression operator<(LinearExpr a, - LinearExpr b) { + public static BoundedLinearExpression operator<(LinearExpr a, LinearExpr b) { return new BoundedLinearExpression(Int64.MinValue, a - b, -1); } @@ -182,7 +177,7 @@ namespace Google.OrTools.Sat { if (v == 1) { return e; } else if (e is ProductCst) { - ProductCst p = (ProductCst) e; + ProductCst p = (ProductCst)e; return new ProductCst(p.Expr, p.Coeff * v); } else { return new ProductCst(e, v); @@ -193,7 +188,7 @@ namespace Google.OrTools.Sat { Dictionary dict) { List exprs = new List(); List coeffs = new List(); - if ((Object) e != null) { + if ((Object)e != null) { exprs.Add(e); coeffs.Add(initial_coeff); } @@ -204,28 +199,29 @@ namespace Google.OrTools.Sat { exprs.RemoveAt(0); long coeff = coeffs[0]; coeffs.RemoveAt(0); - if (coeff == 0 || (Object) expr == null) continue; + if (coeff == 0 || (Object)expr == null) + continue; if (expr is ProductCst) { - ProductCst p = (ProductCst) expr; + ProductCst p = (ProductCst)expr; if (p.Coeff != 0) { exprs.Add(p.Expr); coeffs.Add(p.Coeff * coeff); } } else if (expr is SumArray) { - SumArray a = (SumArray) expr; + SumArray a = (SumArray)expr; constant += coeff * a.Constant; foreach (LinearExpr sub in a.Expressions) { if (sub is IntVar) { - IntVar i = (IntVar) sub; + IntVar i = (IntVar)sub; if (dict.ContainsKey(i)) { dict[i] += coeff; } else { dict.Add(i, coeff); } - } else if (sub is ProductCst && ((ProductCst) sub).Expr is IntVar) { - ProductCst sub_prod = (ProductCst) sub; - IntVar i = (IntVar) sub_prod.Expr; + } else if (sub is ProductCst && ((ProductCst)sub).Expr is IntVar) { + ProductCst sub_prod = (ProductCst)sub; + IntVar i = (IntVar)sub_prod.Expr; long sub_coeff = sub_prod.Coeff; if (dict.ContainsKey(i)) { @@ -239,14 +235,14 @@ namespace Google.OrTools.Sat { } } } else if (expr is IntVar) { - IntVar i = (IntVar) expr; + IntVar i = (IntVar)expr; if (dict.ContainsKey(i)) { dict[i] += coeff; } else { dict.Add(i, coeff); } } else if (expr is NotBooleanVariable) { - IntVar i = ((NotBooleanVariable) expr).NotVar(); + IntVar i = ((NotBooleanVariable)expr).NotVar(); if (dict.ContainsKey(i)) { dict[i] -= coeff; } else { @@ -356,7 +352,7 @@ namespace Google.OrTools.Sat { } public void AddExpr(LinearExpr expr) { - if ((Object) expr != null) { + if ((Object)expr != null) { expressions_.Add(expr); } } @@ -376,7 +372,8 @@ namespace Google.OrTools.Sat { public override string ToString() { string result = ""; foreach (LinearExpr expr in expressions_) { - if ((Object) expr == null) continue; + if ((Object)expr == null) + continue; if (!String.IsNullOrEmpty(result)) { result += String.Format(" + "); } @@ -405,7 +402,9 @@ namespace Google.OrTools.Sat { get { return index_; } } - public override int GetIndex() { return index_; } + public override int GetIndex() { + return index_; + } public IntegerVariableProto Proto { get { return var_; } @@ -416,7 +415,9 @@ namespace Google.OrTools.Sat { get { return SatHelper.VariableDomain(var_); } } - public override string ToString() { return var_.ToString(); } + public override string ToString() { + return var_.ToString(); + } public override string ShortString() { if (var_.Name != null) { @@ -426,13 +427,14 @@ namespace Google.OrTools.Sat { } } - public string Name() { return var_.Name; } + public string Name() { + return var_.Name; + } public ILiteral Not() { foreach (long b in var_.Domain) { if (b < 0 || b > 1) { - throw new ArgumentException( - "Cannot call Not() on a non boolean variable"); + throw new ArgumentException("Cannot call Not() on a non boolean variable"); } } if (negation_ == null) { @@ -449,13 +451,21 @@ namespace Google.OrTools.Sat { } public class NotBooleanVariable : LinearExpr, ILiteral { - public NotBooleanVariable(IntVar boolvar) { boolvar_ = boolvar; } + public NotBooleanVariable(IntVar boolvar) { + boolvar_ = boolvar; + } - public override int GetIndex() { return -boolvar_.Index - 1; } + public override int GetIndex() { + return -boolvar_.Index - 1; + } - public ILiteral Not() { return boolvar_; } + public ILiteral Not() { + return boolvar_; + } - public IntVar NotVar() { return boolvar_; } + public IntVar NotVar() { + return boolvar_; + } public override string ShortString() { return String.Format("Not({0})", boolvar_.ShortString()); @@ -481,8 +491,7 @@ namespace Google.OrTools.Sat { type_ = Type.BoundExpression; } - public BoundedLinearExpression(LinearExpr left, LinearExpr right, - bool equality) { + public BoundedLinearExpression(LinearExpr left, LinearExpr right, bool equality) { left_ = left; right_ = right; lb_ = 0; @@ -500,9 +509,9 @@ namespace Google.OrTools.Sat { bool IsTrue() { if (type_ == Type.VarEqVar) { - return (object) left_ == (object) right_; + return (object)left_ == (object)right_; } else if (type_ == Type.VarDiffVar) { - return (object) left_ != (object) right_; + return (object)left_ != (object)right_; } return false; } @@ -532,38 +541,30 @@ namespace Google.OrTools.Sat { } } - public static BoundedLinearExpression operator <=(BoundedLinearExpression a, - long v) { + public static BoundedLinearExpression operator <=(BoundedLinearExpression a, long v) { if (a.CtType != Type.BoundExpression || a.Ub != Int64.MaxValue) { - throw new ArgumentException( - "Operator <= not supported for this BoundedLinearExpression"); + throw new ArgumentException("Operator <= not supported for this BoundedLinearExpression"); } return new BoundedLinearExpression(a.Lb, a.Left, v); } - public static BoundedLinearExpression operator<(BoundedLinearExpression a, - long v) { + public static BoundedLinearExpression operator<(BoundedLinearExpression a, long v) { if (a.CtType != Type.BoundExpression || a.Ub != Int64.MaxValue) { - throw new ArgumentException( - "Operator < not supported for this BoundedLinearExpression"); + throw new ArgumentException("Operator < not supported for this BoundedLinearExpression"); } return new BoundedLinearExpression(a.Lb, a.Left, v - 1); } - public static BoundedLinearExpression operator >=(BoundedLinearExpression a, - long v) { + public static BoundedLinearExpression operator >=(BoundedLinearExpression a, long v) { if (a.CtType != Type.BoundExpression || a.Lb != Int64.MinValue) { - throw new ArgumentException( - "Operator >= not supported for this BoundedLinearExpression"); + throw new ArgumentException("Operator >= not supported for this BoundedLinearExpression"); } return new BoundedLinearExpression(v, a.Left, a.Ub); } - public static BoundedLinearExpression operator>(BoundedLinearExpression a, - long v) { + public static BoundedLinearExpression operator>(BoundedLinearExpression a, long v) { if (a.CtType != Type.BoundExpression || a.Lb != Int64.MinValue) { - throw new ArgumentException( - "Operator < not supported for this BoundedLinearExpression"); + throw new ArgumentException("Operator < not supported for this BoundedLinearExpression"); } return new BoundedLinearExpression(v + 1, a.Left, a.Ub); } diff --git a/ortools/sat/csharp/IntervalVariables.cs b/ortools/sat/csharp/IntervalVariables.cs index a8cd251109..a7c3664440 100644 --- a/ortools/sat/csharp/IntervalVariables.cs +++ b/ortools/sat/csharp/IntervalVariables.cs @@ -16,8 +16,8 @@ namespace Google.OrTools.Sat { using System.Collections.Generic; public class IntervalVar { - public IntervalVar(CpModelProto model, int start_index, int size_index, - int end_index, int is_present_index, string name) { + public IntervalVar(CpModelProto model, int start_index, int size_index, int end_index, + int is_present_index, string name) { model_ = model; index_ = model.Constraints.Count; interval_ = new IntervalConstraintProto(); @@ -32,8 +32,8 @@ namespace Google.OrTools.Sat { model.Constraints.Add(ct); } - public IntervalVar(CpModelProto model, int start_index, int size_index, - int end_index, string name) { + public IntervalVar(CpModelProto model, int start_index, int size_index, int end_index, + string name) { model_ = model; index_ = model.Constraints.Count; interval_ = new IntervalConstraintProto(); @@ -47,7 +47,9 @@ namespace Google.OrTools.Sat { model_.Constraints.Add(ct); } - public int GetIndex() { return index_; } + public int GetIndex() { + return index_; + } public IntervalConstraintProto Proto { get { return interval_; } @@ -55,12 +57,12 @@ namespace Google.OrTools.Sat { } public override string ToString() { - return model_ - .Constraints [index_] - .ToString(); + return model_.Constraints[index_].ToString(); } - public string Name() { return model_.Constraints[index_].Name; } + public string Name() { + return model_.Constraints[index_].Name; + } private CpModelProto model_; private int index_; diff --git a/ortools/sat/csharp/SearchHelpers.cs b/ortools/sat/csharp/SearchHelpers.cs index 7fd0db6039..02bf0e9248 100644 --- a/ortools/sat/csharp/SearchHelpers.cs +++ b/ortools/sat/csharp/SearchHelpers.cs @@ -29,16 +29,17 @@ namespace Google.OrTools.Sat { exprs.RemoveAt(0); long coeff = coeffs[0]; coeffs.RemoveAt(0); - if (coeff == 0) continue; + if (coeff == 0) + continue; if (expr is ProductCst) { - ProductCst p = (ProductCst) expr; + ProductCst p = (ProductCst)expr; if (p.Coeff != 0) { exprs.Add(p.Expr); coeffs.Add(p.Coeff * coeff); } } else if (expr is SumArray) { - SumArray a = (SumArray) expr; + SumArray a = (SumArray)expr; constant += coeff * a.Constant; foreach (LinearExpr sub in a.Expressions) { exprs.Add(sub); @@ -49,8 +50,7 @@ namespace Google.OrTools.Sat { long value = SolutionIntegerValue(index); constant += coeff * value; } else if (expr is NotBooleanVariable) { - throw new ArgumentException( - "Cannot evaluate a literal in an integer expression."); + throw new ArgumentException("Cannot evaluate a literal in an integer expression."); } else { throw new ArgumentException("Cannot evaluate '" + expr.ToString() + "' in an integer expression"); @@ -74,7 +74,9 @@ namespace Google.OrTools.Sat { private DateTime _startTime; private int _solutionCount; - public ObjectiveSolutionPrinter() { _startTime = DateTime.Now; } + public ObjectiveSolutionPrinter() { + _startTime = DateTime.Now; + } public override void OnSolutionCallback() { var currentTime = DateTime.Now; @@ -85,8 +87,7 @@ namespace Google.OrTools.Sat { var time = currentTime - _startTime; Console.WriteLine( - value - : $"Solution {_solutionCount}, time = {time.TotalSeconds} s, objective = [{objLb}, {objUb}]"); + value: $"Solution {_solutionCount}, time = {time.TotalSeconds} s, objective = [{objLb}, {objUb}]"); _solutionCount++; } diff --git a/ortools/sat/samples/AssignmentSat.cs b/ortools/sat/samples/AssignmentSat.cs index 6c5d51f11d..1e432db0b2 100644 --- a/ortools/sat/samples/AssignmentSat.cs +++ b/ortools/sat/samples/AssignmentSat.cs @@ -21,9 +21,9 @@ public class AssignmentSat { static void Main() { // Data. // [START data_model] - int[, ] costs = { - {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, - {45, 110, 95, 115}, {50, 100, 90, 100}, + int[,] costs = { + { 90, 80, 75, 70 }, { 35, 85, 55, 65 }, { 125, 95, 90, 95 }, + { 45, 110, 95, 115 }, { 50, 100, 90, 100 }, }; int numWorkers = costs.GetLength(0); int numTasks = costs.GetLength(1); @@ -36,7 +36,7 @@ public class AssignmentSat { // Variables. // [START variables] - IntVar[, ] x = new IntVar[numWorkers, numTasks]; + IntVar[,] x = new IntVar[numWorkers, numTasks]; // Variables in a 1-dim array. IntVar[] xFlat = new IntVar[numWorkers * numTasks]; int[] costsFlat = new int[numWorkers * numTasks]; @@ -91,8 +91,7 @@ public class AssignmentSat { for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { if (solver.Value(x[i, j]) > 0.5) { - Console.WriteLine( - $"Worker {i} assigned to task {j}. Cost: {costs[i, j]}"); + Console.WriteLine($"Worker {i} assigned to task {j}. Cost: {costs[i, j]}"); } } } diff --git a/ortools/sat/samples/BinPackingProblemSat.cs b/ortools/sat/samples/BinPackingProblemSat.cs index 3d5f39eb2a..85f3960b95 100644 --- a/ortools/sat/samples/BinPackingProblemSat.cs +++ b/ortools/sat/samples/BinPackingProblemSat.cs @@ -21,19 +21,18 @@ public class BinPackingProblemSat { int slack_capacity = 20; int num_bins = 5; - int[, ] items = new int[, ]{{20, 6}, {15, 6}, {30, 4}, {45, 3}}; + int[,] items = new int[,] { { 20, 6 }, { 15, 6 }, { 30, 4 }, { 45, 3 } }; int num_items = items.GetLength(0); // Model. CpModel model = new CpModel(); // Main variables. - IntVar[, ] x = new IntVar[num_items, num_bins]; + IntVar[,] x = new IntVar[num_items, num_bins]; for (int i = 0; i < num_items; ++i) { int num_copies = items[i, 1]; for (int b = 0; b < num_bins; ++b) { - x[i, b] = - model.NewIntVar(0, num_copies, String.Format("x_{0}_{1}", i, b)); + x[i, b] = model.NewIntVar(0, num_copies, String.Format("x_{0}_{1}", i, b)); } } @@ -77,9 +76,7 @@ public class BinPackingProblemSat { // slack[b] => load[b] <= safe_capacity. model.Add(load[b] <= safe_capacity).OnlyEnforceIf(slacks[b]); // not(slack[b]) => load[b] > safe_capacity. - model.Add(load[b] > safe_capacity) - .OnlyEnforceIf(slacks [b] - .Not()); + model.Add(load[b] > safe_capacity).OnlyEnforceIf(slacks[b].Not()); } // Maximize sum of slacks. @@ -90,23 +87,17 @@ public class BinPackingProblemSat { CpSolverStatus status = solver.Solve(model); Console.WriteLine(String.Format("Solve status: {0}", status)); if (status == CpSolverStatus.Optimal) { - Console.WriteLine( - String.Format("Optimal objective value: {0}", solver.ObjectiveValue)); + Console.WriteLine(String.Format("Optimal objective value: {0}", solver.ObjectiveValue)); for (int b = 0; b < num_bins; ++b) { - Console.WriteLine( - String.Format("load_{0} = {1}", b, solver.Value(load[b]))); + Console.WriteLine(String.Format("load_{0} = {1}", b, solver.Value(load[b]))); for (int i = 0; i < num_items; ++i) { - Console.WriteLine(string.Format(" item_{0}_{1} = {2}", i, b, - solver.Value(x[i, b]))); + Console.WriteLine(string.Format(" item_{0}_{1} = {2}", i, b, solver.Value(x[i, b]))); } } } Console.WriteLine("Statistics"); - Console.WriteLine( - String.Format(" - conflicts : {0}", solver.NumConflicts())); - Console.WriteLine( - String.Format(" - branches : {0}", solver.NumBranches())); - Console.WriteLine( - String.Format(" - wall time : {0} s", solver.WallTime())); + Console.WriteLine(String.Format(" - conflicts : {0}", solver.NumConflicts())); + Console.WriteLine(String.Format(" - branches : {0}", solver.NumBranches())); + Console.WriteLine(String.Format(" - wall time : {0} s", solver.WallTime())); } } diff --git a/ortools/sat/samples/BoolOrSampleSat.cs b/ortools/sat/samples/BoolOrSampleSat.cs index 3b1948620d..ee962b52e1 100644 --- a/ortools/sat/samples/BoolOrSampleSat.cs +++ b/ortools/sat/samples/BoolOrSampleSat.cs @@ -21,6 +21,6 @@ public class BoolOrSampleSat { IntVar x = model.NewBoolVar("x"); IntVar y = model.NewBoolVar("y"); - model.AddBoolOr(new ILiteral[]{x, y.Not()}); + model.AddBoolOr(new ILiteral[] { x, y.Not() }); } } diff --git a/ortools/sat/samples/ChannelingSampleSat.cs b/ortools/sat/samples/ChannelingSampleSat.cs index 46cc96e9e0..2061e98e67 100644 --- a/ortools/sat/samples/ChannelingSampleSat.cs +++ b/ortools/sat/samples/ChannelingSampleSat.cs @@ -16,7 +16,9 @@ using Google.OrTools.Sat; using Google.OrTools.Util; public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { @@ -53,10 +55,9 @@ public class ChannelingSampleSat { model.Add(y == 0).OnlyEnforceIf(b.Not()); // Search for x values in increasing order. - model.AddDecisionStrategy( - new IntVar[]{x}, - DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, - DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); + model.AddDecisionStrategy(new IntVar[] { x }, + DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, + DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); // Create the solver. CpSolver solver = new CpSolver(); @@ -64,8 +65,7 @@ public class ChannelingSampleSat { // Force solver to follow the decision strategy exactly. solver.StringParameters = "search_branching:FIXED_SEARCH"; - VarArraySolutionPrinter cb = - new VarArraySolutionPrinter(new IntVar[]{x, y, b}); + VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, b }); solver.SearchAllSolutions(model, cb); } } diff --git a/ortools/sat/samples/CpIsFunSat.cs b/ortools/sat/samples/CpIsFunSat.cs index 54b2d9f63e..18994aa650 100644 --- a/ortools/sat/samples/CpIsFunSat.cs +++ b/ortools/sat/samples/CpIsFunSat.cs @@ -17,7 +17,9 @@ using Google.OrTools.Sat; // [START solution_printing] public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { @@ -29,7 +31,9 @@ public class VarArraySolutionPrinter : CpSolverSolutionCallback { } } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; private IntVar[] variables_; @@ -57,7 +61,7 @@ public class CpIsFunSat { IntVar e = model.NewIntVar(0, kBase - 1, "E"); // We need to group variables in a list to use the constraint AllDifferent. - IntVar[] letters = new IntVar[]{c, p, i, s, f, u, n, t, r, e}; + IntVar[] letters = new IntVar[] { c, p, i, s, f, u, n, t, r, e }; // [END variables] // [START constraints] @@ -65,8 +69,7 @@ public class CpIsFunSat { model.AddAllDifferent(letters); // CP + IS + FUN = TRUE - model.Add(c * kBase + p + i * kBase + s + f * kBase * kBase + u * kBase + - n == + model.Add(c * kBase + p + i * kBase + s + f * kBase * kBase + u * kBase + n == t * kBase * kBase * kBase + r * kBase * kBase + u * kBase + e); // [END constraints] diff --git a/ortools/sat/samples/EarlinessTardinessCostSampleSat.cs b/ortools/sat/samples/EarlinessTardinessCostSampleSat.cs index 2b5f14f56b..3de7096139 100644 --- a/ortools/sat/samples/EarlinessTardinessCostSampleSat.cs +++ b/ortools/sat/samples/EarlinessTardinessCostSampleSat.cs @@ -16,7 +16,9 @@ using Google.OrTools.Sat; using Google.OrTools.Util; public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { @@ -65,13 +67,12 @@ public class EarlinessTardinessCostSampleSat { model.Add(s3 == lateness_cost * (x - lateness_date)); // Link together expr and x through s1, s2, and s3. - model.AddMaxEquality(expr, new IntVar[]{s1, s2, s3}); + model.AddMaxEquality(expr, new IntVar[] { s1, s2, s3 }); // Search for x values in increasing order. - model.AddDecisionStrategy( - new IntVar[]{x}, - DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, - DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); + model.AddDecisionStrategy(new IntVar[] { x }, + DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, + DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); // Create the solver. CpSolver solver = new CpSolver(); @@ -79,8 +80,7 @@ public class EarlinessTardinessCostSampleSat { // Force solver to follow the decision strategy exactly. solver.StringParameters = "search_branching:FIXED_SEARCH"; - VarArraySolutionPrinter cb = - new VarArraySolutionPrinter(new IntVar[]{x, expr}); + VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, expr }); solver.SearchAllSolutions(model, cb); } } diff --git a/ortools/sat/samples/IntervalSampleSat.cs b/ortools/sat/samples/IntervalSampleSat.cs index f57156fda7..4bccec619c 100644 --- a/ortools/sat/samples/IntervalSampleSat.cs +++ b/ortools/sat/samples/IntervalSampleSat.cs @@ -22,7 +22,6 @@ public class IntervalSampleSat { // C# code supports IntVar or integer constants in intervals. int duration = 10; IntVar end_var = model.NewIntVar(0, horizon, "end"); - IntervalVar interval = - model.NewIntervalVar(start_var, duration, end_var, "interval"); + IntervalVar interval = model.NewIntervalVar(start_var, duration, end_var, "interval"); } } diff --git a/ortools/sat/samples/NoOverlapSampleSat.cs b/ortools/sat/samples/NoOverlapSampleSat.cs index d048fa7767..fddfa13231 100644 --- a/ortools/sat/samples/NoOverlapSampleSat.cs +++ b/ortools/sat/samples/NoOverlapSampleSat.cs @@ -24,22 +24,19 @@ public class NoOverlapSampleSat { IntVar start_0 = model.NewIntVar(0, horizon, "start_0"); int duration_0 = 2; IntVar end_0 = model.NewIntVar(0, horizon, "end_0"); - IntervalVar task_0 = - model.NewIntervalVar(start_0, duration_0, end_0, "task_0"); + IntervalVar task_0 = model.NewIntervalVar(start_0, duration_0, end_0, "task_0"); // Task 1, duration 4. IntVar start_1 = model.NewIntVar(0, horizon, "start_1"); int duration_1 = 4; IntVar end_1 = model.NewIntVar(0, horizon, "end_1"); - IntervalVar task_1 = - model.NewIntervalVar(start_1, duration_1, end_1, "task_1"); + IntervalVar task_1 = model.NewIntervalVar(start_1, duration_1, end_1, "task_1"); // Task 2, duration 3. IntVar start_2 = model.NewIntVar(0, horizon, "start_2"); int duration_2 = 3; IntVar end_2 = model.NewIntVar(0, horizon, "end_2"); - IntervalVar task_2 = - model.NewIntervalVar(start_2, duration_2, end_2, "task_2"); + IntervalVar task_2 = model.NewIntervalVar(start_2, duration_2, end_2, "task_2"); // Weekends. IntervalVar weekend_0 = model.NewIntervalVar(5, 2, 7, "weekend_0"); @@ -47,12 +44,12 @@ public class NoOverlapSampleSat { IntervalVar weekend_2 = model.NewIntervalVar(19, 2, 21, "weekend_2"); // No Overlap constraint. - model.AddNoOverlap(new IntervalVar[]{task_0, task_1, task_2, weekend_0, - weekend_1, weekend_2}); + model.AddNoOverlap( + new IntervalVar[] { task_0, task_1, task_2, weekend_0, weekend_1, weekend_2 }); // Makespan objective. IntVar obj = model.NewIntVar(0, horizon, "makespan"); - model.AddMaxEquality(obj, new IntVar[]{end_0, end_1, end_2}); + model.AddMaxEquality(obj, new IntVar[] { end_0, end_1, end_2 }); model.Minimize(obj); // Creates a solver and solves the model. diff --git a/ortools/sat/samples/OptionalIntervalSampleSat.cs b/ortools/sat/samples/OptionalIntervalSampleSat.cs index 63cd8bf8ec..44aa4acc70 100644 --- a/ortools/sat/samples/OptionalIntervalSampleSat.cs +++ b/ortools/sat/samples/OptionalIntervalSampleSat.cs @@ -23,7 +23,7 @@ public class OptionalIntervalSampleSat { int duration = 10; IntVar end_var = model.NewIntVar(0, horizon, "end"); IntVar presence_var = model.NewBoolVar("presence"); - IntervalVar interval = model.NewOptionalIntervalVar( - start_var, duration, end_var, presence_var, "interval"); + IntervalVar interval = + model.NewOptionalIntervalVar(start_var, duration, end_var, presence_var, "interval"); } } diff --git a/ortools/sat/samples/RabbitsAndPheasantsSat.cs b/ortools/sat/samples/RabbitsAndPheasantsSat.cs index 2b6f4c521a..3bad8a6989 100644 --- a/ortools/sat/samples/RabbitsAndPheasantsSat.cs +++ b/ortools/sat/samples/RabbitsAndPheasantsSat.cs @@ -31,8 +31,7 @@ public class RabbitsAndPheasantsSat { CpSolverStatus status = solver.Solve(model); if (status == CpSolverStatus.Optimal) { - Console.WriteLine(solver.Value(r) + " rabbits, and " + solver.Value(p) + - " pheasants"); + Console.WriteLine(solver.Value(r) + " rabbits, and " + solver.Value(p) + " pheasants"); } } } diff --git a/ortools/sat/samples/RankingSampleSat.cs b/ortools/sat/samples/RankingSampleSat.cs index 422d91bdfc..b5a6aa3355 100644 --- a/ortools/sat/samples/RankingSampleSat.cs +++ b/ortools/sat/samples/RankingSampleSat.cs @@ -16,12 +16,11 @@ using System.Collections.Generic; using Google.OrTools.Sat; public class RankingSampleSat { - static void RankTasks(CpModel model, IntVar[] starts, ILiteral[] presences, - IntVar[] ranks) { + static void RankTasks(CpModel model, IntVar[] starts, ILiteral[] presences, IntVar[] ranks) { int num_tasks = starts.Length; // Creates precedence variables between pairs of intervals. - ILiteral[, ] precedences = new ILiteral[num_tasks, num_tasks]; + ILiteral[,] precedences = new ILiteral[num_tasks, num_tasks]; for (int i = 0; i < num_tasks; ++i) { for (int j = 0; j < num_tasks; ++j) { if (i == j) { @@ -40,38 +39,22 @@ public class RankingSampleSat { List tmp_array = new List(); tmp_array.Add(precedences[i, j]); tmp_array.Add(precedences[j, i]); - tmp_array.Add(presences [i] - .Not()); + tmp_array.Add(presences[i].Not()); // Makes sure that if i is not performed, all precedences are false. - model.AddImplication(presences [i] - .Not(), - precedences [i, j] - .Not()); - model.AddImplication(presences [i] - .Not(), - precedences [j, i] - .Not()); - tmp_array.Add(presences [j] - .Not()); + model.AddImplication(presences[i].Not(), precedences[i, j].Not()); + model.AddImplication(presences[i].Not(), precedences[j, i].Not()); + tmp_array.Add(presences[j].Not()); // Makes sure that if j is not performed, all precedences are false. - model.AddImplication(presences [j] - .Not(), - precedences [i, j] - .Not()); - model.AddImplication(presences [j] - .Not(), - precedences [j, i] - .Not()); + model.AddImplication(presences[j].Not(), precedences[i, j].Not()); + model.AddImplication(presences[j].Not(), precedences[j, i].Not()); // The following bool_or will enforce that for any two intervals: // i precedes j or j precedes i or at least one interval is not // performed. model.AddBoolOr(tmp_array); // Redundant constraint: it propagates early that at most one precedence // is true. - model.AddImplication(precedences[i, j], precedences [j, i] - .Not()); - model.AddImplication(precedences[j, i], precedences [i, j] - .Not()); + model.AddImplication(precedences[i, j], precedences[j, i].Not()); + model.AddImplication(precedences[j, i], precedences[i, j].Not()); } } @@ -79,7 +62,7 @@ public class RankingSampleSat { for (int i = 0; i < num_tasks; ++i) { IntVar[] tmp_array = new IntVar[num_tasks]; for (int j = 0; j < num_tasks; ++j) { - tmp_array[j] = (IntVar) precedences[j, i]; + tmp_array[j] = (IntVar)precedences[j, i]; } model.Add(ranks[i] == LinearExpr.Sum(tmp_array) - 1); } @@ -105,19 +88,17 @@ public class RankingSampleSat { int duration = t + 1; ends[t] = model.NewIntVar(0, horizon, String.Format("end_{0}", t)); if (t < num_tasks / 2) { - intervals[t] = model.NewIntervalVar(starts[t], duration, ends[t], - String.Format("interval_{0}", t)); + intervals[t] = + model.NewIntervalVar(starts[t], duration, ends[t], String.Format("interval_{0}", t)); presences[t] = true_var; } else { presences[t] = model.NewBoolVar(String.Format("presence_{0}", t)); - intervals[t] = model.NewOptionalIntervalVar( - starts[t], duration, ends[t], presences[t], - String.Format("o_interval_{0}", t)); + intervals[t] = model.NewOptionalIntervalVar(starts[t], duration, ends[t], presences[t], + String.Format("o_interval_{0}", t)); } // Ranks = -1 if and only if the tasks is not performed. - ranks[t] = - model.NewIntVar(-1, num_tasks - 1, String.Format("rank_{0}", t)); + ranks[t] = model.NewIntVar(-1, num_tasks - 1, String.Format("rank_{0}", t)); } // Adds NoOverlap constraint. @@ -139,7 +120,7 @@ public class RankingSampleSat { // the solver will not perform the last interval. IntVar[] presences_as_int_vars = new IntVar[num_tasks]; for (int t = 0; t < num_tasks; ++t) { - presences_as_int_vars[t] = (IntVar) presences[t]; + presences_as_int_vars[t] = (IntVar)presences[t]; } model.Minimize(2 * makespan - 7 * LinearExpr.Sum(presences_as_int_vars)); @@ -148,23 +129,19 @@ public class RankingSampleSat { CpSolverStatus status = solver.Solve(model); if (status == CpSolverStatus.Optimal) { - Console.WriteLine( - String.Format("Optimal cost: {0}", solver.ObjectiveValue)); + Console.WriteLine(String.Format("Optimal cost: {0}", solver.ObjectiveValue)); Console.WriteLine(String.Format("Makespan: {0}", solver.Value(makespan))); for (int t = 0; t < num_tasks; ++t) { if (solver.BooleanValue(presences[t])) { - Console.WriteLine( - String.Format("Task {0} starts at {1} with rank {2}", t, - solver.Value(starts[t]), solver.Value(ranks[t]))); + Console.WriteLine(String.Format("Task {0} starts at {1} with rank {2}", t, + solver.Value(starts[t]), solver.Value(ranks[t]))); } else { - Console.WriteLine( - String.Format("Task {0} in not performed and ranked at {1}", t, - solver.Value(ranks[t]))); + Console.WriteLine(String.Format("Task {0} in not performed and ranked at {1}", t, + solver.Value(ranks[t]))); } } } else { - Console.WriteLine( - String.Format("Solver exited with nonoptimal status: {0}", status)); + Console.WriteLine(String.Format("Solver exited with nonoptimal status: {0}", status)); } } } diff --git a/ortools/sat/samples/ReifiedSampleSat.cs b/ortools/sat/samples/ReifiedSampleSat.cs index 9b69147f34..9fe00861eb 100644 --- a/ortools/sat/samples/ReifiedSampleSat.cs +++ b/ortools/sat/samples/ReifiedSampleSat.cs @@ -23,14 +23,14 @@ public class ReifiedSampleSat { IntVar b = model.NewBoolVar("b"); // First version using a half-reified bool and. - model.AddBoolAnd(new ILiteral[]{x, y.Not()}).OnlyEnforceIf(b); + model.AddBoolAnd(new ILiteral[] { x, y.Not() }).OnlyEnforceIf(b); // Second version using implications. model.AddImplication(b, x); model.AddImplication(b, y.Not()); // Third version using bool or. - model.AddBoolOr(new ILiteral[]{b.Not(), x}); - model.AddBoolOr(new ILiteral[]{b.Not(), y.Not()}); + model.AddBoolOr(new ILiteral[] { b.Not(), x }); + model.AddBoolOr(new ILiteral[] { b.Not(), y.Not() }); } } diff --git a/ortools/sat/samples/SearchForAllSolutionsSampleSat.cs b/ortools/sat/samples/SearchForAllSolutionsSampleSat.cs index 773c0efc47..3cb44a7998 100644 --- a/ortools/sat/samples/SearchForAllSolutionsSampleSat.cs +++ b/ortools/sat/samples/SearchForAllSolutionsSampleSat.cs @@ -17,21 +17,24 @@ using Google.OrTools.Sat; // [START print_solution] public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { - Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", - solution_count_, WallTime())); + Console.WriteLine( + String.Format("Solution #{0}: time = {1:F2} s", solution_count_, WallTime())); foreach (IntVar v in variables_) { - Console.WriteLine( - String.Format(" {0} = {1}", v.ShortString(), Value(v))); + Console.WriteLine(String.Format(" {0} = {1}", v.ShortString(), Value(v))); } solution_count_++; } } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; private IntVar[] variables_; @@ -62,13 +65,11 @@ public class SearchForAllSolutionsSampleSat { // Creates a solver and solves the model. // [START solve] CpSolver solver = new CpSolver(); - VarArraySolutionPrinter cb = - new VarArraySolutionPrinter(new IntVar[]{x, y, z}); + VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, z }); solver.SearchAllSolutions(model, cb); // [END solve] - Console.WriteLine( - String.Format("Number of solutions found: {0}", cb.SolutionCount())); + Console.WriteLine(String.Format("Number of solutions found: {0}", cb.SolutionCount())); } } // [END program] diff --git a/ortools/sat/samples/SolutionHintingSampleSat.cs b/ortools/sat/samples/SolutionHintingSampleSat.cs index d8948d3d12..36f2de3645 100644 --- a/ortools/sat/samples/SolutionHintingSampleSat.cs +++ b/ortools/sat/samples/SolutionHintingSampleSat.cs @@ -17,21 +17,24 @@ using Google.OrTools.Sat; // [START print_solution] public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { - Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", - solution_count_, WallTime())); + Console.WriteLine( + String.Format("Solution #{0}: time = {1:F2} s", solution_count_, WallTime())); foreach (IntVar v in variables_) { - Console.WriteLine( - String.Format(" {0} = {1}", v.ShortString(), Value(v))); + Console.WriteLine(String.Format(" {0} = {1}", v.ShortString(), Value(v))); } solution_count_++; } } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; private IntVar[] variables_; @@ -64,15 +67,13 @@ public class SolutionHintingSampleSat { model.AddHint(y, 2); // [START objective] - model.Maximize( - LinearExpr.ScalProd(new IntVar[]{x, y, z}, new int[]{1, 2, 3})); + model.Maximize(LinearExpr.ScalProd(new IntVar[] { x, y, z }, new int[] { 1, 2, 3 })); // [END objective] // Creates a solver and solves the model. // [START solve] CpSolver solver = new CpSolver(); - VarArraySolutionPrinter cb = - new VarArraySolutionPrinter(new IntVar[]{x, y, z}); + VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, y, z }); CpSolverStatus status = solver.SolveWithSolutionCallback(model, cb); // [END solve] } diff --git a/ortools/sat/samples/SolveAndPrintIntermediateSolutionsSampleSat.cs b/ortools/sat/samples/SolveAndPrintIntermediateSolutionsSampleSat.cs index c03c9921e6..f88b8c2ba9 100644 --- a/ortools/sat/samples/SolveAndPrintIntermediateSolutionsSampleSat.cs +++ b/ortools/sat/samples/SolveAndPrintIntermediateSolutionsSampleSat.cs @@ -22,18 +22,17 @@ public class VarArraySolutionPrinterWithObjective : CpSolverSolutionCallback { } public override void OnSolutionCallback() { - Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", - solution_count_, WallTime())); - Console.WriteLine( - String.Format(" objective value = {0}", ObjectiveValue())); + Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", solution_count_, WallTime())); + Console.WriteLine(String.Format(" objective value = {0}", ObjectiveValue())); foreach (IntVar v in variables_) { - Console.WriteLine( - String.Format(" {0} = {1}", v.ShortString(), Value(v))); + Console.WriteLine(String.Format(" {0} = {1}", v.ShortString(), Value(v))); } solution_count_++; } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; private IntVar[] variables_; @@ -70,12 +69,11 @@ public class SolveAndPrintIntermediateSolutionsSampleSat { // [START solve] CpSolver solver = new CpSolver(); VarArraySolutionPrinterWithObjective cb = - new VarArraySolutionPrinterWithObjective(new IntVar[]{x, y, z}); + new VarArraySolutionPrinterWithObjective(new IntVar[] { x, y, z }); solver.SolveWithSolutionCallback(model, cb); // [END solve] - Console.WriteLine( - String.Format("Number of solutions found: {0}", cb.SolutionCount())); + Console.WriteLine(String.Format("Number of solutions found: {0}", cb.SolutionCount())); } } // [END program] diff --git a/ortools/sat/samples/StepFunctionSampleSat.cs b/ortools/sat/samples/StepFunctionSampleSat.cs index 521f38f7d9..0f0ee9d1df 100644 --- a/ortools/sat/samples/StepFunctionSampleSat.cs +++ b/ortools/sat/samples/StepFunctionSampleSat.cs @@ -16,7 +16,9 @@ using Google.OrTools.Sat; using Google.OrTools.Util; public class VarArraySolutionPrinter : CpSolverSolutionCallback { - public VarArraySolutionPrinter(IntVar[] variables) { variables_ = variables; } + public VarArraySolutionPrinter(IntVar[] variables) { + variables_ = variables; + } public override void OnSolutionCallback() { { @@ -51,9 +53,7 @@ public class StepFunctionSampleSat { // expr == 0 on [5, 6] U [8, 10] ILiteral b0 = model.NewBoolVar("b0"); - model - .AddLinearExpressionInDomain( - x, Domain.FromValues(new long[]{5, 6, 8, 9, 10})) + model.AddLinearExpressionInDomain(x, Domain.FromValues(new long[] { 5, 6, 8, 9, 10 })) .OnlyEnforceIf(b0); model.Add(expr == 0).OnlyEnforceIf(b0); @@ -61,8 +61,8 @@ public class StepFunctionSampleSat { ILiteral b2 = model.NewBoolVar("b2"); model .AddLinearExpressionInDomain( - x, Domain.FromIntervals(new long[][]{ - new long[]{0, 1}, new long[]{3, 4}, new long[]{11, 20}})) + x, Domain.FromIntervals(new long[][] { new long[] { 0, 1 }, new long[] { 3, 4 }, + new long[] { 11, 20 } })) .OnlyEnforceIf(b2); model.Add(expr == 2).OnlyEnforceIf(b2); @@ -72,13 +72,12 @@ public class StepFunctionSampleSat { model.Add(expr == 3).OnlyEnforceIf(b3); // At least one bi is true. (we could use a sum == 1). - model.AddBoolOr(new ILiteral[]{b0, b2, b3}); + model.AddBoolOr(new ILiteral[] { b0, b2, b3 }); // Search for x values in increasing order. - model.AddDecisionStrategy( - new IntVar[]{x}, - DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, - DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); + model.AddDecisionStrategy(new IntVar[] { x }, + DecisionStrategyProto.Types.VariableSelectionStrategy.ChooseFirst, + DecisionStrategyProto.Types.DomainReductionStrategy.SelectMinValue); // Create the solver. CpSolver solver = new CpSolver(); @@ -86,8 +85,7 @@ public class StepFunctionSampleSat { // Force solver to follow the decision strategy exactly. solver.StringParameters = "search_branching:FIXED_SEARCH"; - VarArraySolutionPrinter cb = - new VarArraySolutionPrinter(new IntVar[]{x, expr}); + VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] { x, expr }); solver.SearchAllSolutions(model, cb); } } diff --git a/ortools/sat/samples/StopAfterNSolutionsSampleSat.cs b/ortools/sat/samples/StopAfterNSolutionsSampleSat.cs index e6b5413033..7924962f74 100644 --- a/ortools/sat/samples/StopAfterNSolutionsSampleSat.cs +++ b/ortools/sat/samples/StopAfterNSolutionsSampleSat.cs @@ -15,28 +15,26 @@ using System; using Google.OrTools.Sat; public class VarArraySolutionPrinterWithLimit : CpSolverSolutionCallback { - public VarArraySolutionPrinterWithLimit(IntVar[] variables, - int solution_limit) { + public VarArraySolutionPrinterWithLimit(IntVar[] variables, int solution_limit) { variables_ = variables; solution_limit_ = solution_limit; } public override void OnSolutionCallback() { - Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", - solution_count_, WallTime())); + Console.WriteLine(String.Format("Solution #{0}: time = {1:F2} s", solution_count_, WallTime())); foreach (IntVar v in variables_) { - Console.WriteLine( - String.Format(" {0} = {1}", v.ShortString(), Value(v))); + Console.WriteLine(String.Format(" {0} = {1}", v.ShortString(), Value(v))); } solution_count_++; if (solution_count_ >= solution_limit_) { - Console.WriteLine(String.Format("Stopping search after {0} solutions", - solution_limit_)); + Console.WriteLine(String.Format("Stopping search after {0} solutions", solution_limit_)); StopSearch(); } } - public int SolutionCount() { return solution_count_; } + public int SolutionCount() { + return solution_count_; + } private int solution_count_; private IntVar[] variables_; @@ -57,9 +55,8 @@ public class StopAfterNSolutionsSampleSat { // Creates a solver and solves the model. CpSolver solver = new CpSolver(); VarArraySolutionPrinterWithLimit cb = - new VarArraySolutionPrinterWithLimit(new IntVar[]{x, y, z}, 5); + new VarArraySolutionPrinterWithLimit(new IntVar[] { x, y, z }, 5); solver.SearchAllSolutions(model, cb); - Console.WriteLine( - String.Format("Number of solutions found: {0}", cb.SolutionCount())); + Console.WriteLine(String.Format("Number of solutions found: {0}", cb.SolutionCount())); } } diff --git a/ortools/util/csharp/NestedArrayHelper.cs b/ortools/util/csharp/NestedArrayHelper.cs index a0a30f7578..6b8eb7f2c0 100644 --- a/ortools/util/csharp/NestedArrayHelper.cs +++ b/ortools/util/csharp/NestedArrayHelper.cs @@ -19,25 +19,19 @@ namespace Google.OrTools { public static class NestedArrayHelper { public static T[] GetFlatArray(T[][] arr) { int flatLength = 0; - for (var i = 0; i < arr.GetLength(0); i++) - flatLength += arr [i] - .GetLength(0); + for (var i = 0; i < arr.GetLength(0); i++) flatLength += arr[i].GetLength(0); int idx = 0; T[] flat = new T[flatLength]; for (int i = 0; i < arr.GetLength(0); i++) { - for (int j = 0; j < arr [i] - .GetLength(0); - j++) - flat[idx++] = arr [i] - [j]; + for (int j = 0; j < arr[i].GetLength(0); j++) flat[idx++] = arr[i][j]; } return flat; } - public static T[] GetFlatArrayFromMatrix(T[, ] arr) { + public static T[] GetFlatArrayFromMatrix(T[,] arr) { int flatLength = arr.GetLength(0) * arr.GetLength(1); int idx = 0; @@ -53,7 +47,8 @@ namespace Google.OrTools { public static int[] GetArraySecondSize(T[][] arr) { var result = new int[arr.GetLength(0)]; for (var i = 0; i < arr.GetLength(0); i++) { - if (arr[i] != null) result[i] = arr[i].Length; + if (arr[i] != null) + result[i] = arr[i].Length; } return result; }