diff --git "a/verified/dataset_verified.jsonl" "b/verified/dataset_verified.jsonl" new file mode 100644--- /dev/null +++ "b/verified/dataset_verified.jsonl" @@ -0,0 +1,63 @@ +{"id": "csplib__csplib_001_car_sequencing", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/car_sequencing.ipynb", "# Source description: https://www.csplib.org/Problems/prob001/"], "description": "A number of cars are to be produced; they are not identical, because different options are available as variants on the basic model. The assembly line has different stations which install the various options (air-conditioning, sunroof, etc.). These stations have been designed to handle at most a certain percentage of the cars passing along the assembly line. Furthermore, the cars requiring a certain option must not be bunched together, otherwise the station will not be able to cope. Consequently, the cars must be arranged in a sequence so that the capacity of each station is never exceeded. For instance, if a particular station can only cope with at most half of the cars passing along the line, the sequence must be built so that at most 1 car in any 2 requires that option. Print the sequence of car types in the assembly line (sequence); each car type is represented by a number starting from 0.", "input_data": "at_most = [1, 2, 2, 2, 1] # The amount of times a property can be present # in a group of consecutive timeslots (see next variable) per_slots = [2, 3, 3, 5, 5] # The amount of consecutive timeslots demand = [1, 1, 2, 2, 2, 2] # The demand per type of car requires = [[1, 0, 1, 1, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 1], [0, 1, 0, 1, 0], [1, 0, 1, 0, 0], [1, 1, 0, 0, 0]] # The properties per type of car", "model": "# Data\nat_most = [1, 2, 2, 2, 1] # The amount of times a property can be present\n# in a group of consecutive timeslots (see next variable)\nper_slots = [2, 3, 3, 5, 5] # The amount of consecutive timeslots\ndemand = [1, 1, 2, 2, 2, 2] # The demand per type of car\nrequires = [[1, 0, 1, 1, 0],\n [0, 0, 0, 1, 0],\n [0, 1, 0, 0, 1],\n [0, 1, 0, 1, 0],\n [1, 0, 1, 0, 0],\n [1, 1, 0, 0, 0]] # The properties per type of car\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn_cars = sum(demand) # The amount of cars to sequence\nn_options = len(at_most) # The amount of different options\nn_types = len(demand) # The amount of different car types\nrequires = cpm_array(requires) # For element constraint\n\n# Decision Variables\nsequence = intvar(0, n_types - 1, shape=n_cars, name=\"sequence\") # The sequence of car types\nsetup = boolvar(shape=(n_cars, n_options), name=\"setup\") # Sequence of different options based on the car type\n\n# Model\nmodel = Model()\n\n# The amount of each type of car in the sequence has to be equal to the demand for that type\nmodel += [sum(sequence == t) == demand[t] for t in range(n_types)]\n\n# Make sure that the options in the setup table correspond to those of the car type\nfor s in range(n_cars):\n model += [setup[s, o] == requires[sequence[s], o] for o in range(n_options)]\n\n# Check that no more than \"at most\" car options are used per \"per_slots\" slots\nfor o in range(n_options):\n for s in range(n_cars - per_slots[o]):\n slot_range = range(s, s + per_slots[o])\n model += (sum(setup[slot_range, o]) <= at_most[o])\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"sequence\": sequence.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["sequence"]} +{"id": "csplib__csplib_005_autocorrelation", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob005_auto_correlation.py", "# Source description: https://www.csplib.org/Problems/prob005/"], "description": "These problems have many practical applications in communications and electrical engineering. The objective is to construct a binary sequence of length n that minimizes the autocorrelations between bits. Each bit in the sequence takes the value +1 or -1. With non-periodic (or open) boundary conditions, the k-th autocorrelation, Ck is defined to be \\[ C_k = \\sum_{i=0}^{n-k-1} S_i \\cdot S_{i+k} \\]. With periodic (or cyclic) boundary conditions, the k-th autocorrelation, Ck is defined to be \\[ C_k = \\sum_{i=0}^{n-1} S_i \\cdot S_{(i+k) \\mod n} \\]. The aim is to minimize the sum of the squares of these autocorrelations. That is, to minimize \\[ E = \\sum_{k=1}^{n-1} C_k^2 \\]. Print the binary sequence (sequence) and the energy value (E).", "input_data": "n = 10 # Length of the binary sequence", "model": "# Data\nn = 10 # Length of the binary sequence\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n\n# periodic auto correlation\ndef PAF(arr, s):\n # roll the array 's' indices\n return sum(arr * np.roll(arr, -s))\n\n\n# Decision Variables\nsequence = intvar(-1, 1, shape=n, name=\"sequence\") # binary sequence\nE = sum([PAF(sequence, s) ** 2 for s in range(1, n)]) # energy value\n\nmodel = Model()\n\n# exclude 0\nmodel += sequence != 0\n\n# minimize sum of squares\nmodel.minimize(E)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"sequence\": sequence.value().tolist(), \"E\": E.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["sequence", "E"]} +{"id": "csplib__csplib_008_vessel_loading", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob008_vessel_loading.py", "# Source description: https://www.csplib.org/Problems/prob008/"], "description": "Supply vessels transport containers from site to site. The deck area is rectangular. Containers are cuboid, and are laid out in a single layer. All containers are positioned parallel to the sides of the deck. The contents of the containers determine their class. Certain classes of containers are constrained to be separated by minimum distances either along the deck or across the deck. The vessel loading decision problem is to determine whether a given set of containers can be positioned on a given deck, without overlapping, and without violating any of the separation constraints. The problem can be modelled as packing of a set of rectangles into a larger rectangle, subject to constraints. In practice, the layout may be further constrained by the physical loading sequence. Containers are manoeuvred into position from the southeast corner. Each successive container in the loading sequence must be positioned so that it touches part of another container or a deck wall both to the north and to the west. Print the positions of the containers (left, right, top, bottom).", "input_data": "deck_width = 5 # Width of the deck deck_length = 5 # Length of the deck n_containers = 3 # Number of containers width = [5, 2, 3] # Widths of containers length = [1, 4, 4] # Lengths of containers classes = [1, 1, 1] # Classes of containers separation = [ # Separation constraints between classes [0, 0], [0, 0] ]", "model": "# Data\ndeck_width = 5 # Width of the deck\ndeck_length = 5 # Length of the deck\nn_containers = 3 # Number of containers\nwidth = [5, 2, 3] # Widths of containers\nlength = [1, 4, 4] # Lengths of containers\nclasses = [1, 1, 1] # Classes of containers\nseparation = [ # Separation constraints between classes\n [0, 0],\n [0, 0]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nfrom cpmpy.expressions.utils import all_pairs\n\n# Create the model\nmodel = Model()\n\n# Declare variables\nleft = intvar(0, deck_width, shape=n_containers, name=\"left\")\nright = intvar(0, deck_width, shape=n_containers, name=\"right\")\ntop = intvar(0, deck_length, shape=n_containers, name=\"top\")\nbottom = intvar(0, deck_length, shape=n_containers, name=\"bottom\")\n\n# Set shape of containers\nfor i in range(n_containers):\n model += ((right[i] - left[i] == width[i]) & (top[i] - bottom[i] == length[i])) | \\\n ((right[i] - left[i] == length[i]) & (top[i] - bottom[i] == width[i]))\n\n# No overlap between containers\nfor x, y in all_pairs(range(n_containers)):\n c1, c2 = classes[x], classes[y]\n sep = separation[c1 - 1][c2 - 1]\n model += (\n (right[x] + sep <= left[y]) | # x at least sep left of y or\n (left[x] >= right[y] + sep) | # x at least sep right of y or\n (top[x] + sep <= bottom[y]) | # x at least sep under y or\n (bottom[x] >= top[y] + sep) # x at least sep above y\n )\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"left\": left.value().tolist(),\n \"right\": right.value().tolist(),\n \"top\": top.value().tolist(),\n \"bottom\": bottom.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["right", "top", "left", "bottom"]} +{"id": "csplib__csplib_009_perfect_square_placement", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob009_perfect_squares.py", "# Source description: https://www.csplib.org/Problems/prob009/"], "description": "The perfect square placement problem (also called the squared square problem) is to pack a set of squares with given integer sizes into a bigger square in such a way that no squares overlap each other and all square borders are parallel to the border of the big square. For a perfect placement problem, all squares have different sizes. The sum of the square surfaces is equal to the surface of the packing square, so that there is no spare capacity. A simple perfect square placement problem is a perfect square placement problem in which no subset of the squares (greater than one) are placed in a rectangle. Print the coordinates of the squares (x_coords, y_coords).", "input_data": "base = 6 # Side length of the large square sides = [3, 3, 3, 2, 1, 1, 1, 1, 1] # Side lengths of the smaller squares", "model": "# Data\nbase = 6 # Side length of the large square\nsides = [3, 3, 3, 2, 1, 1, 1, 1, 1] # Side lengths of the smaller squares\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\ndef perfect_squares(base, sides):\n model = Model()\n sides = np.array(sides)\n\n squares = range(len(sides))\n\n # Ensure that the squares cover the base exactly\n assert np.square(sides).sum() == base ** 2, \"Squares do not cover the base exactly!\"\n\n # Variables\n x_coords = intvar(0, base, shape=len(squares), name=\"x_coords\")\n y_coords = intvar(0, base, shape=len(squares), name=\"y_coords\")\n\n # Squares must be in bounds of big square\n model += x_coords + sides <= base\n model += y_coords + sides <= base\n\n # No overlap between squares\n for a, b in all_pairs(squares):\n model += (\n (x_coords[a] + sides[a] <= x_coords[b]) |\n (x_coords[b] + sides[b] <= x_coords[a]) |\n (y_coords[a] + sides[a] <= y_coords[b]) |\n (y_coords[b] + sides[b] <= y_coords[a])\n )\n\n return model, (x_coords, y_coords)\n\n# Example usage\nmodel, (x_coords, y_coords) = perfect_squares(base, sides)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"x_coords\": x_coords.value().tolist(),\n \"y_coords\": y_coords.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["y_coords", "x_coords"]} +{"id": "csplib__csplib_012_nonogram", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob012_nonogram.py", "# Source description: https://www.csplib.org/Problems/prob012/"], "description": "Nonograms are a popular puzzle, which goes by different names in different countries. Solvers have to shade in squares in a grid so that blocks of consecutive shaded squares satisfy constraints given for each row and column. Constraints typically indicate the sequence of shaded blocks (e.g. 3,1,2 means that there is a block of 3, then a gap of unspecified size, a block of length 1, another gap, and then a block of length 2). Print the solution board (board).", "input_data": "rows = 8 # Number of rows row_rule_len = 2 # Maximum length of row rules row_rules = [ [0, 1], [0, 2], [4, 4], [0, 12], [0, 8], [0, 9], [3, 4], [2, 2] ] # Rules for rows cols = 13 # Number of columns col_rule_len = 2 # Maximum length of column rules col_rules = [ [0, 2], [2, 1], [3, 2], [0, 6], [1, 4], [0, 3], [0, 4], [0, 4], [0, 4], [0, 5], [0, 4], [1, 3], [0, 2] ] # Rules for columns", "model": "# Data\nrows = 8 # Number of rows\nrow_rule_len = 2 # Maximum length of row rules\nrow_rules = [\n [0, 1],\n [0, 2],\n [4, 4],\n [0, 12],\n [0, 8],\n [0, 9],\n [3, 4],\n [2, 2]\n] # Rules for rows\ncols = 13 # Number of columns\ncol_rule_len = 2 # Maximum length of column rules\ncol_rules = [\n [0, 2],\n [2, 1],\n [3, 2],\n [0, 6],\n [1, 4],\n [0, 3],\n [0, 4],\n [0, 4],\n [0, 4],\n [0, 5],\n [0, 4],\n [1, 3],\n [0, 2]\n] # Rules for columns\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\n\n\ndef nonogram(row_rules, col_rules, **kwargs):\n solver = SolverLookup.get(\"ortools\")\n n_rows, n_cols = len(row_rules), len(col_rules)\n board = intvar(0, 1, shape=(n_rows, n_cols), name=\"board\")\n solver.user_vars.update(set(board.flatten()))\n\n # Patterns of each row must be correct\n for r, pattern in enumerate(row_rules):\n automaton_func, final_states = transition_function(pattern)\n solver.ort_model.AddAutomaton(\n solver.solver_vars(board[r]),\n starting_state=0, final_states=final_states,\n transition_triples=automaton_func\n )\n\n # Patterns of each column must be correct\n for c, pattern in enumerate(col_rules):\n automaton_func, final_states = transition_function(pattern)\n solver.ort_model.AddAutomaton(\n solver.solver_vars(board[:, c]),\n starting_state=0, final_states=final_states,\n transition_triples=automaton_func\n )\n\n return solver, (board,)\n\n\ndef transition_function(pattern):\n \"\"\"\n Pattern is a vector containing the lengths of blocks with value 1\n \"\"\"\n func = []\n n_states = 0\n for block_length in pattern:\n if block_length == 0:\n continue\n func += [(n_states, 0, n_states)]\n for _ in range(block_length):\n func += [(n_states, 1, n_states + 1)]\n n_states += 1\n\n func += [(n_states, 0, n_states + 1)]\n n_states += 1\n\n func += [(n_states, 0, n_states)]\n # Line can end with 0 or 1\n return func, [n_states - 1, n_states]\n\n\n# Example usage\nmodel, (board,) = nonogram(row_rules, col_rules)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"board\": board.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["board"]} +{"id": "csplib__csplib_015_schurs_lemma", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob015_shur_lemma.py", "# Source description: https://www.csplib.org/Problems/prob015/"], "description": "The problem is to put \\( n \\) balls labelled \\( 1, \\ldots, n \\) into 3 boxes so that for any triple of balls \\( (x, y, z) \\) with \\( x + y = z \\), not all are in the same box. This has a solution iff \\( n < 14 \\). The problem can be formulated as a 0-1 problem using the variables \\( M_{ij} \\) for \\( i \\in \\{1, \\ldots, n\\}, j \\in \\{1, 2, 3\\} \\) with \\( M_{ij} \\) true if ball \\( i \\) is in box \\( j \\). The constraints are that a ball must be in exactly one box, \\( M_{i1} + M_{i2} + M_{i3} = 1 \\) for all \\( i \\in \\{1, \\ldots, n\\} \\). And for each \\( x + y = z \\) and \\( j \\in \\{1, 2, 3\\} \\), not \\( (M_{xj} \\land M_{yj} \\land M_{zj}) \\). This converts to, \\( (1 - M_{xj}) + (1 - M_{yj}) + (1 - M_{zj}) \\geq 1 \\) or, \\( M_{xj} + M_{yj} + M_{zj} \\leq 2 \\). Print the assignment of balls to boxes (balls) as a list of n integers from 1 to 3.", "input_data": "n = 13 # Number of balls c = 3 # Number of boxes", "model": "# Data\nn = 13 # Number of balls\nc = 3 # Number of boxes\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\n\n\ndef shur_lemma(n, c):\n # balls[i] = j iff ball i is in box j\n balls = intvar(1, c, shape=n, name=\"balls\")\n\n model = Model()\n\n # Ensure each triple (x, y, z) with x + y = z are not in the same box\n for x in range(1, n):\n for y in range(1, n - x + 1):\n z = x + y\n if z <= n:\n model += (balls[x - 1] != balls[y - 1]) | \\\n (balls[x - 1] != balls[z - 1]) | \\\n (balls[y - 1] != balls[z - 1])\n\n return model, (balls,)\n\n\n# Example usage\nmodel, (balls,) = shur_lemma(n, c)\nmodel.solve()\n\n# Print\nsolution = {\"balls\": balls.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["balls"]} +{"id": "csplib__csplib_021_crossfigures", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/crossfigure.py", "# Source description: https://www.csplib.org/Problems/prob021/", "# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"], "description": "Crossfigures are the numerical equivalent of crosswords. You have a grid and some clues with numerical answers to place on this grid. Clues come in several different forms (for example: Across 1. 25 across times two, 2. five dozen, 5. a square number, 10. prime, 14. 29 across times 21 down ...). Here is the specific problem: 1 2 3 4 5 6 7 8 9 --------------------------- 1 2 _ 3 X 4 _ 5 6 1 7 _ X 8 _ _ X 9 _ 2 _ X 10 _ X 11 12 X _ 3 13 14 _ _ X 15 _ 16 _ 4 X _ X X X X X _ X 5 17 _ 18 19 X 20 21 _ 22 6 _ X 23 _ X 24 _ X _ 7 25 26 X 27 _ _ X 28 _ 8 29 _ _ _ X 30 _ _ _ 9 Here are the clues: # Across # 1 27 across times two # 4 4 down plus seventy-one # 7 18 down plus four # 8 6 down divided by sixteen # 9 2 down minus eighteen # 10 Dozen in six gross # 11 5 down minus seventy # 13 26 down times 23 across # 15 6 down minus 350 # 17 25 across times 23 across # 20 A square number # 23 A prime number # 24 A square number # 25 20 across divided by seventeen # 27 6 down divided by four # 28 Four dozen # 29 Seven gross # 30 22 down plus 450 # Down # # 1 1 across plus twenty-seven # 2 Five dozen # 3 30 across plus 888 # 4 Two times 17 across # 5 29 across divided by twelve # 6 28 across times 23 across # 10 10 across plus four # 12 Three times 24 across # 14 13 across divided by sixteen # 16 28 down times fifteen # 17 13 across minus 399 # 18 29 across divided by eighteen # 19 22 down minus ninety-four # 20 20 across minus nine # 21 25 across minus fifty-two # 22 20 down times six # 26 Five times 24 across # 28 21 down plus twenty-seven Print the solved crossfigure as a list of lists of integers (M).", "input_data": "", "model": "# Import libraries\nimport math\nfrom cpmpy import *\nimport json\n\n\ndef member_of(x, val):\n \"\"\"\n member_of(x, val)\n\n Ensures that the value `val` is in the array `x`.\n \"\"\"\n n = len(x)\n # cc = intvar(0,n)\n # constraints = [count(x, val, cc), cc > 0]\n constraints = [sum([x[i] == val for i in range(n)]) > 0]\n return constraints\n\n\ndef is_prime(n):\n \"\"\"\n is_prime(n)\n\n Returns True if the number n is a prime number, otherwise return False.\n \"\"\"\n if n < 2: return False\n if n == 2: return True\n if not n & 1:\n return False\n for i in range(3, 1 + int(math.sqrt(n)), 2):\n if n % i == 0:\n return False\n return True\n\n\ndef to_num(a, n, base):\n \"\"\"\n to_num(a, n, base)\n\n Ensure that the digits in array `a` corresponds to the number `n` in base `base`.\n \"\"\"\n tlen = len(a)\n return n == sum([(base ** (tlen - i - 1)) * a[i] for i in range(tlen)])\n\n\n#\n# across(Matrix, Across, Len, Row, Col)\n# Constrains 'Across' to be equal to the number represented by the\n# 'Len' digits starting at position (Row, Col) of the array 'Matrix'\n# and proceeding across.\n#\ndef across(Matrix, Across, Len, Row, Col):\n Row -= 1\n Col -= 1\n tmp = intvar(0, 9999, shape=Len)\n constraints = []\n constraints += [to_num(tmp, Across, 10)]\n for i in range(Len):\n constraints += [Matrix[Row, Col + i] == tmp[i]]\n return constraints\n\n\n#\n# down(Matrix, Down, Len, Row, Col):\n#\tConstrains 'Down' to be equal to the number represented by the\n#\t'Len' digits starting at position (Row, Col) of the array 'Matrix'\n#\tand proceeding down.\n#\ndef down(Matrix, Down, Len, Row, Col):\n Row -= 1\n Col -= 1\n tmp = intvar(0, 9999, shape=Len)\n constraints = []\n constraints += [to_num(tmp, Down, 10)]\n for i in range(Len):\n constraints += [Matrix[Row + i, Col] == tmp[i]]\n return constraints\n\n\nmodel = Model()\nn = 9\n\nD = 9999 # the max length of the numbers in this problem is 4\nprimes = [i for i in range(2, D + 1) if is_prime(i)]\nsquares = [i ** 2 for i in range(1, 1 + math.ceil(math.sqrt(D)))]\n\nZ = -1\nB = -2 # Black box\n# The valid squares (or rather the invalid are marked as B)\nValid = [[Z, Z, Z, Z, B, Z, Z, Z, Z],\n [Z, Z, B, Z, Z, Z, B, Z, Z],\n [Z, B, Z, Z, B, Z, Z, B, Z],\n [Z, Z, Z, Z, B, Z, Z, Z, Z],\n [B, Z, B, B, B, B, B, Z, B],\n [Z, Z, Z, Z, B, Z, Z, Z, Z],\n [Z, B, Z, Z, B, Z, Z, B, Z],\n [Z, Z, B, Z, Z, Z, B, Z, Z],\n [Z, Z, Z, Z, B, Z, Z, Z, Z]]\n\nM = intvar(0, 9, shape=(n, n), name=\"M\") # The matrix\n\nfor i in range(n):\n for j in range(n):\n if Valid[i][j] == B:\n model += (M[i, j] == 0)\n\nA1 = intvar(0, D, name=\"A1\")\nA4 = intvar(0, D, name=\"A4\")\nA7 = intvar(0, D, name=\"A7\")\nA8 = intvar(0, D, name=\"A8\")\nA9 = intvar(0, D, name=\"A9\")\nA10 = intvar(0, D, name=\"A10\")\nA11 = intvar(0, D, name=\"A11\")\nA13 = intvar(0, D, name=\"A13\")\nA15 = intvar(0, D, name=\"A15\")\nA17 = intvar(0, D, name=\"A17\")\nA20 = intvar(0, D, name=\"A20\")\nA23 = intvar(0, D, name=\"A23\")\nA24 = intvar(0, D, name=\"A24\")\nA25 = intvar(0, D, name=\"A25\")\nA27 = intvar(0, D, name=\"A27\")\nA28 = intvar(0, D, name=\"A28\")\nA29 = intvar(0, D, name=\"A29\")\nA30 = intvar(0, D, name=\"A30\")\n\nAList = [A1, A4, A7, A8, A9, A10, A11, A13, A15, A17, A20, A23, A24, A25, A27, A28, A29, A30]\n\nD1 = intvar(0, D, name=\"D1\")\nD2 = intvar(0, D, name=\"D2\")\nD3 = intvar(0, D, name=\"D3\")\nD4 = intvar(0, D, name=\"D4\")\nD5 = intvar(0, D, name=\"D5\")\nD6 = intvar(0, D, name=\"D6\")\nD10 = intvar(0, D, name=\"D10\")\nD12 = intvar(0, D, name=\"D12\")\nD14 = intvar(0, D, name=\"D14\")\nD16 = intvar(0, D, name=\"D16\")\nD17 = intvar(0, D, name=\"D17\")\nD18 = intvar(0, D, name=\"D18\")\nD19 = intvar(0, D, name=\"D19\")\nD20 = intvar(0, D, name=\"D20\")\nD21 = intvar(0, D, name=\"D21\")\nD22 = intvar(0, D, name=\"D22\")\nD26 = intvar(0, D, name=\"D26\")\nD28 = intvar(0, D, name=\"D28\")\nDList = [D1, D2, D3, D4, D5, D6, D10, D12, D14, D17, D18, D19, D20, D21, D22, D26, D28]\n\n# Set up the constraints between the matrix elements and the\n# clue numbers.\n#\n# Note: Row/Col are adjusted to base-0 in the\n# across and down methods.\n#\nmodel += (across(M, A1, 4, 1, 1))\nmodel += (across(M, A4, 4, 1, 6))\nmodel += (across(M, A7, 2, 2, 1))\nmodel += (across(M, A8, 3, 2, 4))\nmodel += (across(M, A9, 2, 2, 8))\nmodel += (across(M, A10, 2, 3, 3))\nmodel += (across(M, A11, 2, 3, 6))\nmodel += (across(M, A13, 4, 4, 1))\nmodel += (across(M, A15, 4, 4, 6))\nmodel += (across(M, A17, 4, 6, 1))\nmodel += (across(M, A20, 4, 6, 6))\nmodel += (across(M, A23, 2, 7, 3))\nmodel += (across(M, A24, 2, 7, 6))\nmodel += (across(M, A25, 2, 8, 1))\nmodel += (across(M, A27, 3, 8, 4))\nmodel += (across(M, A28, 2, 8, 8))\nmodel += (across(M, A29, 4, 9, 1))\nmodel += (across(M, A30, 4, 9, 6))\n\nmodel += (down(M, D1, 4, 1, 1))\nmodel += (down(M, D2, 2, 1, 2))\nmodel += (down(M, D3, 4, 1, 4))\nmodel += (down(M, D4, 4, 1, 6))\nmodel += (down(M, D5, 2, 1, 8))\nmodel += (down(M, D6, 4, 1, 9))\nmodel += (down(M, D10, 2, 3, 3))\nmodel += (down(M, D12, 2, 3, 7))\nmodel += (down(M, D14, 3, 4, 2))\nmodel += (down(M, D16, 3, 4, 8))\nmodel += (down(M, D17, 4, 6, 1))\nmodel += (down(M, D18, 2, 6, 3))\nmodel += (down(M, D19, 4, 6, 4))\nmodel += (down(M, D20, 4, 6, 6))\nmodel += (down(M, D21, 2, 6, 7))\nmodel += (down(M, D22, 4, 6, 9))\nmodel += (down(M, D26, 2, 8, 2))\nmodel += (down(M, D28, 2, 8, 8))\n\n# Set up the clue constraints.\n# Across\n# 1 27 across times two\n# 4 4 down plus seventy-one\n# 7 18 down plus four\n# 8 6 down divided by sixteen\n# 9 2 down minus eighteen\n# 10 Dozen in six gross\n# 11 5 down minus seventy\n# 13 26 down times 23 across\n# 15 6 down minus 350\n# 17 25 across times 23 across\n# 20 A square number\n# 23 A prime number\n# 24 A square number\n# 25 20 across divided by seventeen\n# 27 6 down divided by four\n# 28 Four dozen\n# 29 Seven gross\n# 30 22 down plus 450\n\nmodel += (A1 == 2 * A27)\nmodel += (A4 == D4 + 71)\nmodel += (A7 == D18 + 4)\n# model += (A8 == D6 / 16)\nmodel += (16 * A8 == D6)\nmodel += (A9 == D2 - 18)\n# model += (A10 == 6 * 144 / 12)\nmodel += (12 * A10 == 6 * 144)\nmodel += (A11 == D5 - 70)\nmodel += (A13 == D26 * A23)\nmodel += (A15 == D6 - 350)\nmodel += (A17 == A25 * A23)\n# model += (square(A20))\nmodel += (member_of(squares, A20))\n# model += (is_prime(A23))\nmodel += (member_of(primes, A23))\n# model += (square(A24))\nmodel += (member_of(squares, A24))\n# model += (A25 == A20 / 17)\nmodel += (17 * A25 == A20)\n# model += (A27 == D6 / 4)\nmodel += (4 * A27 == D6)\nmodel += (A28 == 4 * 12)\nmodel += (A29 == 7 * 144)\nmodel += (A30 == D22 + 450)\n\n# Down\n#\n# 1 1 across plus twenty-seven\n# 2 Five dozen\n# 3 30 across plus 888\n# 4 Two times 17 across\n# 5 29 across divided by twelve\n# 6 28 across times 23 across\n# 10 10 across plus four\n# 12 Three times 24 across\n# 14 13 across divided by sixteen\n# 16 28 down times fifteen\n# 17 13 across minus 399\n# 18 29 across divided by eighteen\n# 19 22 down minus ninety-four\n# 20 20 across minus nine\n# 21 25 across minus fifty-two\n# 22 20 down times six\n# 26 Five times 24 across\n# 28 21 down plus twenty-seven\n\nmodel += (D1 == A1 + 27)\nmodel += (D2 == 5 * 12)\nmodel += (D3 == A30 + 888)\nmodel += (D4 == 2 * A17)\n# model += (D5 == A29 / 12)\nmodel += (12 * D5 == A29)\nmodel += (D6 == A28 * A23)\nmodel += (D10 == A10 + 4)\nmodel += (D12 == A24 * 3)\n# model += (D14 == A13 / 16)\nmodel += (16 * D14 == A13)\nmodel += (D16 == 15 * D28)\nmodel += (D17 == A13 - 399)\n# model += (D18 == A29 / 18)\nmodel += (18 * D18 == A29)\nmodel += (D19 == D22 - 94)\nmodel += (D20 == A20 - 9)\nmodel += (D21 == A25 - 52)\nmodel += (D22 == 6 * D20)\nmodel += (D26 == 5 * A24)\nmodel += (D28 == D21 + 27)\n\nmodel.solve()\n\n# Print the solution\nsolution = {\"M\": M.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["M"]} +{"id": "csplib__csplib_053_graceful_graphs", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob053_gracefull_graphs.py", "# Source description: https://www.csplib.org/Problems/prob053/"], "description": "A labelling \\( f \\) of the nodes of a graph with \\( q \\) edges is graceful if \\( f \\) assigns each node a unique label from \\( \\{0, 1, \\ldots, q\\} \\) and when each edge \\( xy \\) is labelled with \\( |f(x) - f(y)| \\), the edge labels are all different. Gallian surveys graceful graphs, i.e., graphs with a graceful labelling, and lists the graphs whose status is known. All-Interval Series is a special case of a graceful graph where the graph is a line. Print the node labels and edge labels (nodes, edges).", "input_data": "m = 16 # Number of edges in the graph n = 8 # Number of nodes in the graph graph = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3], [4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7], [0, 4], [1, 5], [2, 6], [3, 7]] # Edges of the graph", "model": "# Data\nm = 16 # Number of edges in the graph\nn = 8 # Number of nodes in the graph\ngraph = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3],\n [4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7],\n [0, 4], [1, 5], [2, 6], [3, 7]] # Edges of the graph\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nimport numpy as np\n\n\ndef graceful_graphs(m, n, graph):\n graph = np.array(graph)\n\n model = Model()\n\n # variables\n nodes = intvar(0, m, shape=n, name=\"nodes\")\n edges = intvar(1, m, shape=m, name=\"edges\")\n\n # constraints\n model += np.abs(nodes[graph[:, 0]] - nodes[graph[:, 1]]) == edges\n\n model += (AllDifferent(edges))\n model += (AllDifferent(nodes))\n\n return model, (nodes, edges)\n\n\n# Example usage\nmodel, (nodes, edges) = graceful_graphs(m, n, graph)\nmodel.solve()\n\n# Print\nsolution = {\"nodes\": nodes.value().tolist(), \"edges\": edges.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["edges", "nodes"]} +{"id": "csplib__csplib_084_hadamard_matrix", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob084_hadamard_matrix.py", "# Source description: https://www.csplib.org/Problems/prob084/"], "description": "For every odd positive integer \\( \\ell \\) (and \\( m = \\frac{\\ell - 1}{2} \\)) we define the 2cc Hadamard matrix Legendre pairs CSP using the \\{V, D, C\\} format (Variables, Domains, Constraints) as follows: - \\( V = \\{a_1, \\ldots, a_\\ell, b_1, \\ldots, b_\\ell\\} \\), a set of \\( 2 \\cdot \\ell \\) variables - \\( D = \\{D_{a_1}, \\ldots, D_{a_\\ell}, D_{b_1}, \\ldots, D_{b_\\ell}\\} \\), a set of \\( 2 \\cdot \\ell \\) domains, all of them equal to \\{-1, +1\\} - \\( C = \\{c_1, \\ldots, c_m, c_{m+1}, c_{m+2}\\} \\), a set of \\( m+2 \\) constraints (\\( m \\) quadratic constraints and 2 linear constraints) The \\( m \\) quadratic constraints are given by: \\[ c_s := \\text{PAF}(A, s) + \\text{PAF}(B, s) = -2, \\forall s = 1, \\ldots, m \\] where PAF denotes the periodic autocorrelation function: (\\(i + s\\) is taken mod \\( \\ell \\) when it exceeds \\( \\ell \\)) \\[ A = [a_1, \\ldots, a_\\ell], \\, \\text{PAF}(A, s) = \\sum_{i=1}^\\ell a_i a_{i+s} \\] \\[ B = [b_1, \\ldots, b_\\ell], \\, \\text{PAF}(B, s) = \\sum_{i=1}^\\ell b_i b_{i+s} \\] The 2 linear constraints are given by: \\[ c_{m+1} := a_1 + \\ldots + a_\\ell = 1 \\] \\[ c_{m+2} := b_1 + \\ldots + b_\\ell = 1 \\] The 2cc Hadamard matrix Legendre pairs CSP for all odd \\( \\ell = 3, \\ldots, 99 \\) are given in http://www.cargo.wlu.ca/CSP_2cc_Hadamard/ (and in the data section). There are 49 CSPs. All of them are known to have solutions. It is conjectured that the 2cc Hadamard matrix Legendre pairs CSP has solutions, for every odd \\( \\ell \\), and this is linked to the famous Hadamard conjecture [Kotsireas]. Print the variables a and b (a, b).", "input_data": "l = 9 # Value of l (must be an odd positive integer)", "model": "# Data\nl = 9 # Value of l (must be an odd positive integer)\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef PAF(arr, s):\n return sum(arr * np.roll(arr,-s))\n\ndef hadamard_matrix(l=5):\n\n m = int((l - 1) / 2)\n\n a = intvar(-1,1, shape=l, name=\"a\")\n b = intvar(-1,1, shape=l, name=\"b\")\n\n model = Model()\n\n model += a != 0 # exclude 0 from dom\n model += b != 0 # exclude 0 from dom\n\n model += sum(a) == 1\n model += sum(b) == 1\n\n for s in range(1,m+1):\n model += (PAF(a,s) + PAF(b,s)) == -2\n\n return model, (a,b)\n\n\n# Example usage\nmodel, (a, b) = hadamard_matrix(l)\nmodel.solve()\n\n# Print\nsolution = {\"a\": a.value().tolist(), \"b\": b.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["b", "a"]} +{"id": "hakan_examples__abbots_puzzle", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/abbots_puzzle.py"], "description": "If 100 bushels of corn were distributed among 100 people such that each man received three bushels, each woman two, and each child half a bushel, and there are five times as many women as men, find the number of men, women, and children. Print the number of men, women, and children (men, women, children).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\nmen = intvar(0, 100, name=\"men\")\nwomen = intvar(0, 100, name=\"women\")\nchildren = intvar(0, 100, name=\"children\")\n\n# Model\nmodel = Model([\n men + women + children == 100, # Total number of people\n men * 6 + women * 4 + children == 200, # Total bushels of corn\n men * 5 == women # Five times as many women as men\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"men\": men.value(),\n \"women\": women.value(),\n \"children\": children.value()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["men", "women", "children"]} +{"id": "hakan_examples__added_corners", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/added_corner.py"], "description": "Enter the digits 1 through 8 in the circles and squares such that the number in each square is equal to the sum of the numbers in the adjoining circles. ... C F C F F C F C ''' Print the values for each position (positions).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = 8 # Number of digits\n\n# Decision variables\npositions = intvar(1, n, shape=n, name=\"positions\")\na, b, c, d, e, f, g, h = positions\n\n# Model\nmodel = Model([\n AllDifferent(positions),\n b == a + c,\n d == a + f,\n e == c + h,\n g == f + h\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"positions\": positions.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["positions"]} +{"id": "hakan_examples__ages_of_the_sons", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/ages_of_the_sons.py", "# Source description: http://blog.athico.com/2007/08/drools-puzzle-round-1-ages-of-sons.html"], "description": "An old man asked a mathematician to guess the ages of his three sons. Old man said: \"The product of their ages is 36.\" Mathematician said: \"I need more information.\" Old man said:\"Over there you can see a building. The sum of their ages equals the number of the windows in that building.\" After a short while the mathematician said: \"I need more information.\" Old man said: \"The oldest son has blue eyes.\" Mathematician said: \"I got it.\" What are the ages of the three sons of the old man? Print the ages of the sons (A1, A2, A3) starting from the oldest.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n\nA1 = intvar(0, 36, name=\"A1\") # oldest son\nA2 = intvar(0, 36, name=\"A2\")\nA3 = intvar(0, 36, name=\"A3\")\n\nB1 = intvar(0, 36, name=\"B1\")\nB2 = intvar(0, 36, name=\"B2\")\nB3 = intvar(0, 36, name=\"B3\")\nAS = intvar(0, 1000, name=\"AS\")\nBS = intvar(0, 1000, name=\"BS\")\n\nmodel = Model([A1 > A2,\n A2 >= A3,\n 36 == A1 * A2 * A3,\n\n B1 >= B2,\n B2 >= B3,\n A1 != B1,\n\n 36 == B1 * B2 * B3,\n AS == A1 + A2 + A3,\n BS == B1 + B2 + B3,\n AS == BS\n ])\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"A1\": A1.value(), \"A2\": A2.value(), \"A3\": A3.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["A3", "A1", "A2"]} +{"id": "hakan_examples__allergy", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/allergy.py"], "description": "Four friends (two women named Debra and Janet, and two men named Hugh and Rick) found that each of them is allergic to something different: eggs, mold, nuts and ragweed. We would like to match each one's surname (Baxter, Lemon, Malone and Fleet) with his or her allergy. We know that: - Rick is not allergic to mold - Baxter is allergic to eggs - Hugh is neither surnamed Lemon nor Fleet - Debra is allergic to ragweed - Janet (who isn't Lemon) is neither allergic to eggs nor to mold Print the values of each food (eggs, mold, nuts, ragweed) and surname (baxter, lemon, malone, fleet) for each friend, where Debra = 0, Janet = 1, Hugh = 2, Rick = 3.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\nn = 4\nfriends = Debra, Janet, Hugh, Rick = list(range(n))\nfriends_s = [\"Debra\", \"Janet\", \"Hugh\", \"Rick\"]\n\n# foods[i] is the friend allergic to the ith food\neggs, mold, nuts, ragweed = foods = intvar(0, n - 1, shape=n, name=\"foods\")\nfoods_s = [\"eggs\", \"mold\", \"nuts\", \"ragweed\"]\n\n# surnames[i] is the friend with the ith surname\nbaxter, lemon, malone, fleet = surnames = intvar(0, n - 1, shape=n, name=\"surnames\")\nsurnames_s = [\"baxter\", \"lemon\", \"malone\", \"fleet\"]\n\nmodel = Model([AllDifferent(foods),\n AllDifferent(surnames),\n\n mold != Rick,\n eggs == baxter,\n lemon != Hugh,\n fleet != Hugh,\n ragweed == Debra,\n lemon != Janet,\n eggs != Janet,\n mold != Janet])\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"eggs\": eggs.value(), \"mold\": mold.value(), \"nuts\": nuts.value(), \"ragweed\": ragweed.value(),\n \"baxter\": baxter.value(), \"lemon\": lemon.value(), \"malone\": malone.value(), \"fleet\": fleet.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["malone", "baxter", "nuts", "ragweed", "mold", "fleet", "lemon", "eggs"]} +{"id": "hakan_examples__appointment_scheduling", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/appointment_scheduling.py", "# Source description: http://stackoverflow.com/questions/11143439/appointment-scheduling-algorithm-n-people-with-n-free-busy-slots-constraint-sa"], "description": "Schedule 4 people into 4 interview slots based on their free-busy schedules. Print the assignment of people to slots (x) where 1 means the person is assigned to the slot and 0 means the person is not assigned to the slot.", "input_data": "m = [ [1, 1, 1, 1], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1] ] # Matrix representing the free-busy schedules", "model": "# Data\nm = [\n [1, 1, 1, 1],\n [0, 1, 1, 0],\n [1, 0, 0, 1],\n [1, 0, 0, 1]\n] # Matrix representing the free-busy schedules\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nimport random\n\nmodel = Model()\n\nn = len(m)\n\n# decision variables\n\n# the assignment of persons to a slot (appointment number 0..n)\nx = boolvar(shape=(n, n), name=\"x\")\n\n# constraints\n\nfor i in range(n):\n # ensure a free slot\n model += (sum([m[i][j] * x[(i, j)] for j in range(n)]) == 1)\n\n # ensure one assignment per slot\n model += (sum([x[(i, j)] for j in range(n)]) == 1)\n model += (sum([x[(j, i)] for j in range(n)]) == 1)\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"id": "hakan_examples__archery_puzzle", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/archery_puzzle.py"], "description": "How close can the young archer come to scoring a total of 100 using as many arrows as she pleases? The targets are: 16, 17, 23, 24, 39, 40. Print the number of hits on each target (hits).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\ntargets = [16, 17, 23, 24, 39, 40]\nn = len(targets)\ntarget_score = 100\n\n# Decision variables\nhits = intvar(0, 100, shape=n, name=\"hits\")\nscore = intvar(0, 100, name=\"score\")\ndeviation = intvar(0, 100, name=\"deviation\")\n\n# Model\nmodel = Model([\n score == sum(hits * targets),\n deviation == abs(target_score - score)\n])\n\n# Objective\nmodel.minimize(deviation)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"hits\": hits.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["hits"]} +{"id": "hakan_examples__assignment_costs", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/assignment.py", "# Source description: Winston 'Operations Research', Assignment Problems, page 393f"], "description": "Assign people to 4 tasks with different costs, so that the total cost is minimized. Each task must be assigned to exactly one person, but it is not necessary to assign all people to a task. Print whether each task is assigned to a person (x), where 1 means the task is assigned to the person and 0 means the task is not assigned to the person.", "input_data": "cost = [ # Cost matrix, rows are tasks, columns are people [14, 5, 8, 7, 15], [2, 12, 6, 5, 3], [7, 8, 3, 9, 7], [2, 4, 6, 10, 1] ] # Cost matrix", "model": "# Data\ncost = [ # Cost matrix, rows are tasks, columns are people\n [14, 5, 8, 7, 15],\n [2, 12, 6, 5, 3],\n [7, 8, 3, 9, 7],\n [2, 4, 6, 10, 1]\n] # Cost matrix\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Parameters\nrows = len(cost)\ncols = len(cost[0])\n\n# Decision variables\nmax_cost = np.sum(np.array(cost))\n\ntotal_cost = intvar(0, max_cost, name='cost')\nx = boolvar(shape=(rows, cols), name=\"x\")\n\nmodel = Model(\n total_cost >= 0,\n total_cost == np.sum([x_row * cost_row for (x_row, cost_row) in zip(x, cost)]),\n\n # exacly one assignment per row, all rows (tasks) must be assigned.\n [sum(row) == 1 for row in x],\n\n # zero or one assignments per column (people)\n [sum(col) <= 1 for col in x.transpose()],\n)\n\n# Objective\nmodel.minimize(total_cost)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"id": "hakan_examples__autoref", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/autoref.py", "# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"], "description": "Given an integer n > 0 and an integer m >= 0, find a non-empty finite series S=(s0, s1, ..., sn, sn+1) such that ( 1) there are si occurrences of i in S for each integer i ranging from 0 to n, and (2) sn+1=m. Print the series S (s).", "input_data": "n = 27 m = 5", "model": "# Data\nn = 27\nm = 5\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n\ndef count(a, val, c):\n \"\"\"\n count(a,val,c)\n\n c is the number of occurrences of val in array a.\n \"\"\"\n return [c == sum([a[i] == val for i in range(len(a))])]\n\n\ndef global_cardinality_count(a, gcc):\n \"\"\"\n global_cardinality_count(a, gcc)\n\n Global cardinality count: Collect the number of occurrences of each value 0..a.ub\n in gcc. The array gcc must be of length 0..ub.\n \"\"\"\n n = len(a)\n ub = max([a[i].ub for i in range(n)])\n constraints = []\n for i in range(ub + 1):\n constraints += [count(a, i, gcc[i])]\n\n return constraints\n\n\ndef autoref(s):\n \"\"\"\n autoref(s)\n Ensure that the number of occurrences of i in s is s[i].\n s should be an array of 0..n+1\n \"\"\"\n return [global_cardinality_count(s, s)]\n\n\n# Decision Variables\ns = intvar(0, n, shape=n + 2, name=\"s\")\n\n# Model\nmodel = Model(s[n + 1] == m, autoref(s))\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"s\": s.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["s"]} +{"id": "hakan_examples__bin_packing", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/bin_packing.py"], "description": "Given several items of specific weights and a number of bins of a fixed capacity, assign each item to a bin so that the total weight of the items in each bin does not exceed the capacity. Print the bin each item is assigned to (bins) as a list of numbers.", "input_data": "weights = [4, 3, 1, 3, 2, 5, 2] capacity = 5 num_bins = 5", "model": "# Data\nweights = [4, 3, 1, 3, 2, 5, 2]\ncapacity = 5\nnum_bins = 5\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = len(weights)\n\n# Decision variables\nbins = intvar(0, num_bins - 1, shape=n, name=\"bins\") # Which bin each item is assigned to\n\n# Model\nmodel = Model([\n [sum(weights[j] * (bins[j] == i) for j in range(n)) <= capacity for i in range(n)]\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"bins\": bins.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["bins"]} +{"id": "hakan_examples__cabling", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/cabling.py", "# Source description: https://yurichev.com/blog/cabling_Z3/", "# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"], "description": "Take a rack cabinet, like this one: [ an image ] Let's say, there are 8 1U devices, maybe servers, routers and whatnot, named as A, B, C, D, E, F, G, H. Devices must be connected by cables: probably twisted pair or whatever network engineers using today. Some devices must be connected by several cables (2 cables, 3 or 4): A <--- 1 cable ---> H A <--- 2 cables ---> E B <--- 4 cables ---> F C <--- 1 cable ---> G C <--- 1 cable ---> D C <--- 1 cable ---> E D <--- 3 cables ---> H G <--- 1 cable ---> H The problem: how we can place these 8 devices in such an order, so that sum of all cable lengths would be as short as possible? Print the optimal sum of all cable lengths (final_sum).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = 8\n\nmodel = Model()\n\n# A <--- 1 cable ---> H\n# A <--- 2 cables ---> E\n# B <--- 4 cables ---> F\n# C <--- 1 cable ---> G\n# C <--- 1 cable ---> D\n# C <--- 1 cable ---> E\n# D <--- 3 cables ---> H\n# G <--- 1 cable ---> H\nA, B, C, D, E, F, G, H = list(range(n))\n\ncable_struct = [[A, H, 1],\n [A, E, 2],\n [B, F, 4],\n [C, G, 1],\n [C, D, 1],\n [C, E, 1],\n [D, H, 3],\n [G, H, 1]]\n\nx = intvar(0, n - 1, shape=n, name=\"x\") # position of the device in the rack\nt = intvar(1, n * n, shape=len(cable_struct), name=\"t\") # cable lengths\nfinal_sum = intvar(0, n * n, name=\"final_sum\") # sum of all cable lengths\n\n# all \"devices\" has distinct positions in rack:\nmodel += [AllDifferent(x),\n final_sum == sum(t)]\n\nfor i in range(len(cable_struct)):\n a, b, num = cable_struct[i]\n model += [t[i] == abs(x[a] - x[b]) * num]\n\nmodel.minimize(final_sum)\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"final_sum\": final_sum.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["final_sum"]} +{"id": "hakan_examples__candies", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/candies.py"], "description": "Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each child.Children get jealous of their immediate neighbors, so if two children sit next to each other then the one with the higher rating must get more candies. Alice wants to save money, so she wants to minimize the total number of candies. Print the optimal number of candies needed in total (z).", "input_data": "ratings = [2, 3, 4, 4, 4, 2, 1, 3, 4] # Ratings of the children", "model": "# Data\nratings = [2, 3, 4, 4, 4, 2, 1, 3, 4] # Ratings of the children\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = len(ratings)\n\n# variables\nx = intvar(1, n, shape=n, name=\"x\") # number of candies for each child\nz = intvar(1, n * n, name=\"z\") # total number of candies\n\n# constraints\nmodel = Model([z == sum(x),\n z >= n])\n\nfor i in range(1, n):\n if ratings[i - 1] > ratings[i]:\n model += (x[i - 1] > x[i])\n elif ratings[i - 1] < ratings[i]:\n model += (x[i - 1] < x[i])\n\nmodel.minimize(z)\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"z\": z.value(), \"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["z"]} +{"id": "hakan_examples__capital_budget", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/capital_budget.py", "# Source description: Winston 'Operations Research', page 478: Capital budgeting"], "description": "Stockco is considering four investments. Investment 1 will yield a net present value (NPV) of $16,000; investment 2, an NPV of $22,000; investment 3, an NPV of $12,000; and investment 4, an NPV of $8,000. Each investment requires a certain cash outflow at the present time: investment 1, $5,000; investment 2, $7,000; investment 3, $4,000; and investment 4, $3,000. Currently, $14,000 is available for investment. How to maximize the NPV obtained from investments 1–4? Print whether each investment is chosen (x) as a list of 0/1 values.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nbudget = 14\nnpv = [16, 22, 12, 8]\ncash_flow = [5, 7, 4, 3]\nn = 4\n\n# variables\nx = boolvar(shape=n, name=\"x\") # x[i] = 1 if investments i\nz = intvar(0, 1000, name=\"z\") # total NPV\n\n# constraints\nmodel = Model([\n # the sum of all choosen investments must be less than the budget\n sum(x * cash_flow) <= budget,\n z == sum(x * npv)\n])\n\n# Objective: maximize the NPV\nmodel.maximize(z)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"z\": z.value(), \"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"id": "hakan_examples__chess_set", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/chess_set.py", "# Source description: Applications of Optimization with XPress-MP.pdf page 11. The problem is presented on page 7."], "description": "A small joinery makes two different sizes of boxwood chess sets. The small set requires 3 hours of machining on a lathe, and the large set requires 2 hours. There are four lathes with skilled operators who each work a 40 hour week, so we have 160 lathe-hours per week. The small chess set requires 1 kg of boxwood, and the large set requires 3 kg. Unfortunately, boxwood is scarce and only 200 kg per week can be obtained. When sold, each of the large chess sets yields a profit of $20, and one of the small chess set has a profit of $5. The problem is to decide how many sets of each kind should be made each week so as to maximize profit. Print the number of small sets and large sets, and the maximum profit (small_set, large_set, max_profit).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\nsmall_set = intvar(0, 100, name=\"small_set\")\nlarge_set = intvar(0, 100, name=\"large_set\")\nmax_profit = intvar(0, 10000, name=\"max_profit\")\n\n# Model\nmodel = Model([\n small_set + 3 * large_set <= 200, # Boxwood constraint\n 3 * small_set + 2 * large_set <= 160, # Lathe-hours constraint\n max_profit == 5 * small_set + 20 * large_set # Profit calculation\n])\n\n# Objective: maximize the profit\nmodel.maximize(max_profit)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"small_set\": small_set.value(),\n \"large_set\": large_set.value(),\n \"max_profit\": max_profit.value()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["large_set", "small_set", "max_profit"]} +{"id": "hakan_examples__circling_squares", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/circling_squares.py", "# Source description: From the Oz examples http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/circlingsquares.html from 'Amusements in Mathematics, Dudeney', number 43."], "description": "Circling the squares: The puzzle is to place a different number in each of the ten squares so that the sum of the squares of any two adjacent numbers shall be equal to the sum of the squares of the two numbers diametrically opposite to them. The four numbers placed, as examples, must stand as they are. The square of 16 is 256, and the square of 2 is 4. Add these together, and the result is 260. Also—the square of 14 is 196, and the square of 8 is 64. These together also make 260. Now, in precisely the same way, B and C should be equal to G and H (the sum will not necessarily be 260), A and K to F and E, H and I to C and D, and so on, with any two adjoining squares in the circle. All you have to do is to fill in the remaining six numbers. Fractions are not allowed, and I shall show that no number need contain more than two figures. Print the 10 numbers in the circle (A, B, C, D, E, F, G, H, I, K) when A=16, B=2, F=8, G=14.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n\ndef s(x1, x2, y1, y2):\n return x1 * x1 + x2 * x2 == y1 * y1 + y2 * y2\n\n\nn = 10\n\n# variables\nx = intvar(1, 99, shape=n, name=\"x\")\nA, B, C, D, E, F, G, H, I, K = x\n\n# constraints\nmodel = Model([AllDifferent(x),\n A == 16,\n B == 2,\n F == 8,\n G == 14,\n\n s(A, B, F, G),\n s(B, C, G, H),\n s(C, D, H, I),\n s(D, E, I, K),\n s(E, F, K, A),\n ])\n# End of CPMPy script\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"A\": A.value(), \"B\": B.value(), \"C\": C.value(), \"D\": D.value(), \"E\": E.value(),\n \"F\": F.value(), \"G\": G.value(), \"H\": H.value(), \"I\": I.value(), \"K\": K.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["H", "D", "K", "G", "E", "C", "I", "F", "A", "B"]} +{"id": "hakan_examples__coin3_application", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/coins3.py", "# Source description: From 'Constraint Logic Programming using ECLiPSe' pages 99f and 234 ff. The solution in ECLiPSe is at page 236."], "description": "Find the minimum number of coins that allows one to pay exactly any amount smaller than one Euro using the denominations 1, 2, 5, 10, 20, 50 cents. Print the number of each type of coin used (x) as a list.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\ndenominations = [1, 2, 5, 10, 20, 50] # Euro cent denominations\nn = len(denominations)\n\n# declare variables\nx = intvar(0, 99, shape=n, name=\"x\") # The number of each type of coin used\nnum_coins = intvar(0, 99, name=\"num_coins\") # The total number of coins used\n\nmodel = Model(minimize=num_coins)\n\n# constraints\n\n# number of used coins, to be minimized\nmodel += [num_coins == sum(x)]\n\n# Check that all changes from 1 to 99 can be made.\nfor j in range(1, 100):\n tmp = intvar(0, 99, shape=n)\n model += [sum(tmp * denominations) == j]\n model += [tmp[i] <= x[i] for i in range(n)]\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"id": "hakan_examples__coins_grid", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/coins_grid.py", "# Source description: Tony Hurlimann: \"A coin puzzle - SVOR-contest 2007\" http://www.svor.ch/competitions/competition2007/AsroContestSolution.pdf"], "description": "In a quadratic grid (or a larger chessboard) with 31x31 cells, one should place coins in such a way that the following conditions are fulfilled: 1. In each row exactly 14 coins must be placed. 2. In each column exactly 14 coins must be placed. 3. The sum of the quadratic horizontal distance from the main diagonal of all cells containing a coin must be as small as possible. 4. In each cell at most one coin can be placed. The description says to place 14x31 = 434 coins on the chessboard each row containing 14 coins and each column also containing 14 coins. Print whether a coin is placed in each cell (x) as a list of 0/1 lists, and the sum of the quadratic horizontal distance from the main diagonal (z) as a number.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\nimport numpy as np\n\n# Parameters\nn = 31\nc = 14\n\n# variables\nx = intvar(0, 1, shape=(n, n), name=\"x\") # The coins on the grid (1 if a coin is placed, 0 otherwise)\nz = intvar(0, 1000000, name=\"z\") # The sum of the quadratic horizontal distance from the main diagonal\n\nmodel = Model([\n # every row adds up to c\n [sum(row) == c for row in x],\n\n # every col adds up to c\n [sum(col) == c for col in x.transpose()],\n\n # quadratic horizonal distance\n z == sum([x[i, j] * abs(i - j) * abs(i - j) for i in range(0, n) for j in range(0, n)]),\n\n], minimize=z\n)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"x\": x.value().tolist(), \"z\": z.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x", "z"]} +{"id": "hakan_examples__contracting_costs", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/contracting_costs.py", "# Source description: http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/index.html Contracting Costs from 'Mathematical Puzzles of Sam Loyd, Volume 2', number 20."], "description": "A contractor planning the construction of a house found that he would have to pay: * $ 1,100 to the paper hanger and the painter, * $ 1,700 to the painter and plumber, * $ 1,100 to the plumber and electrician, * $ 3,300 to the electrician and carpenter, * $ 5,300 to the carpenter and mason, * $ 3,200 to the mason and painter. What does each man charge for his services? Print the cost of each person's service (paper_hanger, painter, plumber, electrician, carpenter, mason) in dollars.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\nn = 6\nx = intvar(1, 5300, shape=n, name=\"x\")\npaper_hanger, painter, plumber, electrician, carpenter, mason = x\n\ncosts = [[paper_hanger, painter, 1100],\n [painter, plumber, 1700],\n [plumber, electrician, 1100],\n [electrician, carpenter, 3300],\n [carpenter, mason, 5300],\n [mason, painter, 3200],\n ]\n\n# model = Model([1100 == paper_hanger + painter,\n# 1700 == painter + plumber,\n# 1100 == plumber + electrician,\n# 3300 == electrician + carpenter,\n# 5300 == carpenter + mason,\n# 3200 == mason + painter,\n# ])\n\n# Alternative encoding:\nmodel = Model([sum(costs[i][:2]) == costs[i][2] for i in range(n)])\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"paper_hanger\": paper_hanger.value(), \"painter\": painter.value(), \"plumber\": plumber.value(),\n \"electrician\": electrician.value(), \"carpenter\": carpenter.value(), \"mason\": mason.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["painter", "plumber", "electrician", "carpenter", "mason", "paper_hanger"]} +{"id": "hakan_examples__covering_opl", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/covering_opl.py", "# Source description: This example is from the OPL example covering.mod"], "description": "Select a set of workers to perform all the tasks, while minimizing the cost. Each worker can perform certain tasks and has a hiring cost. Ensure that all tasks are performed. Print the total cost (total_cost) and whether each worker is selected (workers) as a list of 0/1 values.", "input_data": "nb_workers = 32 # Number of workers num_tasks = 15 # Number of tasks Qualified = [ # Which worker is qualified for each task (1-based indexing) [1, 9, 19, 22, 25, 28, 31], [2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32], [3, 10, 19, 24, 26, 30, 32], [4, 21, 25, 28, 32], [5, 11, 16, 22, 23, 27, 31], [6, 20, 24, 26, 30, 32], [7, 12, 17, 25, 30, 31], [8, 17, 20, 22, 23], [9, 13, 14, 26, 29, 30, 31], [10, 21, 25, 31, 32], [14, 15, 18, 23, 24, 27, 30, 32], [18, 19, 22, 24, 26, 29, 31], [11, 20, 25, 28, 30, 32], [16, 19, 23, 31], [9, 18, 26, 28, 31, 32]] Cost = [ # Cost of hiring each worker 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 ]", "model": "# Data\nnb_workers = 32 # Number of workers\nnum_tasks = 15 # Number of tasks\nQualified = [ # Which worker is qualified for each task (1-based indexing)\n [1, 9, 19, 22, 25, 28, 31],\n [2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32],\n [3, 10, 19, 24, 26, 30, 32], [4, 21, 25, 28, 32],\n [5, 11, 16, 22, 23, 27, 31], [6, 20, 24, 26, 30, 32],\n [7, 12, 17, 25, 30, 31], [8, 17, 20, 22, 23],\n [9, 13, 14, 26, 29, 30, 31], [10, 21, 25, 31, 32],\n [14, 15, 18, 23, 24, 27, 30, 32], [18, 19, 22, 24, 26, 29, 31],\n [11, 20, 25, 28, 30, 32], [16, 19, 23, 31],\n [9, 18, 26, 28, 31, 32]]\nCost = [ # Cost of hiring each worker\n 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,\n 5, 6, 6, 6, 7, 8, 9\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nWorkers = list(range(nb_workers))\nTasks = list(range(num_tasks))\n\n#\n# variables\n#\nworkers = boolvar(shape=nb_workers, name=\"workers\") # 1 if the worker is hired, 0 otherwise\ntotal_cost = intvar(0, nb_workers * sum(Cost), name=\"total_cost\") # Total cost of hiring the workers\n\nmodel = Model(minimize=total_cost)\n\n#\n# constraints\n#\nmodel += [total_cost == sum(workers * Cost)]\n\nfor j in Tasks:\n # Sum the cost for hiring the qualified workers\n # (also, make 0-base)\n model += [sum([workers[c - 1] for c in Qualified[j]]) >= 1]\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"total_cost\": total_cost.value(), \"workers\": workers.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["total_cost", "workers"]} +{"id": "hakan_examples__crossword", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/crossword2.py", "# Source description: http://www.cis.temple.edu/~ingargio/cis587/readings/constraints.html"], "description": "We are to complete the puzzle 1 2 3 4 5 +---+---+---+---+---+ Given the list of words: 1 | 1 | | 2 | | 3 | AFT LASER +---+---+---+---+---+ ALE LEE 2 | # | # | | # | | EEL LINE +---+---+---+---+---+ HEEL SAILS 3 | # | 4 | | 5 | | HIKE SHEET +---+---+---+---+---+ HOSES STEER 4 | 6 | # | 7 | | | KEEL TIE +---+---+---+---+---+ KNOT 5 | 8 | | | | | +---+---+---+---+---+ 6 | | # | # | | # | The numbers 1,2,3,4,5,6,7,8 in the crossword +---+---+---+---+---+ puzzle correspond to the words that will start at those locations. Print the selected words (E) as a list of 8 integers starting from 0. Assume that the words are first sorted starting from the longest word and then alphabetically. So, word 0 corresponds to HOSES, ..., word 14 corresponds to TIE.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\na = 1;\nb = 2;\nc = 3;\nd = 4;\ne = 5;\nf = 6;\ng = 7;\nh = 8;\ni = 9;\nj = 10;\nk = 11;\nl = 12;\nm = 13;\nn = 14;\no = 15;\np = 16;\nq = 17;\nr = 18;\ns = 19;\nt = 20;\nu = 21;\nv = 22;\nw = 23;\nx = 24;\ny = 25;\nz = 26;\n\nAA = [\n [h, o, s, e, s], # HOSES\n [l, a, s, e, r], # LASER\n [s, a, i, l, s], # SAILS\n [s, h, e, e, t], # SHEET\n [s, t, e, e, r], # STEER\n [h, e, e, l, 0], # HEEL\n [h, i, k, e, 0], # HIKE\n [k, e, e, l, 0], # KEEL\n [k, n, o, t, 0], # KNOT\n [l, i, n, e, 0], # LINE\n [a, f, t, 0, 0], # AFT\n [a, l, e, 0, 0], # ALE\n [e, e, l, 0, 0], # EEL\n [l, e, e, 0, 0], # LEE\n [t, i, e, 0, 0] # TIE\n]\nword_len = 5\nnum_words = len(AA)\n\nnum_overlapping = 12\noverlapping = [\n [0, 2, 1, 0], # s\n [0, 4, 2, 0], # s\n\n [3, 1, 1, 2], # i\n [3, 2, 4, 0], # k\n [3, 3, 2, 2], # e\n\n [6, 0, 1, 3], # l\n [6, 1, 4, 1], # e\n [6, 2, 2, 3], # e\n\n [7, 0, 5, 1], # l\n [7, 2, 1, 4], # s\n [7, 3, 4, 2], # e\n [7, 4, 2, 4] # r\n]\n\nA = intvar(0, 26, shape=(num_words, word_len), name=\"A\")\n\nn = 8\nE = intvar(0, num_words, shape=n, name=\"E\") # The selected words for each slot\n\nmodel = Model()\n\nfor I in range(num_words):\n for J in range(word_len):\n model += [A[I, J] == AA[I][J]]\n\nmodel += [AllDifferent(E)]\n\nfor I in range(num_overlapping):\n model += [A[E[overlapping[I][0]], overlapping[I][1]] == A[E[overlapping[I][2]], overlapping[I][3]]]\n\nmodel.solve()\n\n# Print the solution\nsolution = {\"E\": E.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["E"]} +{"id": "hakan_examples__crypta", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/crypta.py", "# Source description: Name: crypta.pl, Title: crypt-arithmetic, Original Source: P. Van Hentenryck's book, Adapted by: Daniel Diaz - INRIA France, Date: September 1992"], "description": "Cryptarithmetic puzzle, solve the operation: B A I J J A J I I A H F C F E B B J E A + D H F G A B C D I D B I F F A G F E J E ----------------------------------------- = G J E G A C D D H F A F J B F I H E E F where all letters are distinct digits. Print the number of each letter (A, B, C, D, E, F, G, H, I, J).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\nmodel = Model()\n\n# variables\nLD = intvar(0, 9, shape=10, name=\"LD\")\nA, B, C, D, E, F, G, H, I, J = LD\n\nSr1 = intvar(0, 1, name=\"Sr1\")\nSr2 = intvar(0, 1, name=\"Sr2\")\n\n#\n# constraints\n#\nmodel += [AllDifferent(LD)]\nmodel += [B >= 1]\nmodel += [D >= 1]\nmodel += [G >= 1]\n\nmodel += [A + 10 * E + 100 * J + 1000 * B + 10000 * B + 100000 * E +\n 1000000 * F + E + 10 * J + 100 * E + 1000 * F + 10000 * G +\n 100000 * A + 1000000 * F == F + 10 * E + 100 * E + 1000 * H +\n 10000 * I + 100000 * F + 1000000 * B + 10000000 * Sr1]\n\nmodel += [C + 10 * F + 100 * H + 1000 * A + 10000 * I + 100000 * I +\n 1000000 * J + F + 10 * I + 100 * B + 1000 * D + 10000 * I +\n 100000 * D + 1000000 * C + Sr1 == J + 10 * F + 100 * A + 1000 * F +\n 10000 * H + 100000 * D + 1000000 * D + 10000000 * Sr2]\n\nmodel += [A + 10 * J + 100 * J + 1000 * I + 10000 * A + 100000 * B + B +\n 10 * A + 100 * G + 1000 * F + 10000 * H + 100000 * D + Sr2 == C +\n 10 * A + 100 * G + 1000 * E + 10000 * J + 100000 * G]\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"A\": A.value(), \"B\": B.value(), \"C\": C.value(), \"D\": D.value(), \"E\": E.value(), \"F\": F.value(),\n \"G\": G.value(), \"H\": H.value(), \"I\": I.value(), \"J\": J.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["H", "D", "J", "G", "E", "C", "I", "F", "A", "B"]} +{"id": "hakan_examples__eighteen_hole_golf", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/18_hole_golf.py"], "description": "Generate a random 18-hole golf course where each hole has a length of 3, 4, or 5, and the total length of the course is 72. Print the lengths of the holes (holes).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nnum_holes = 18 # Number of holes\ntotal_length = 72 # Total length of the course\nhole_lengths = [3, 4, 5] # Possible lengths for each hole\n\n# Decision variables\nholes = intvar(3, 5, shape=num_holes, name=\"holes\") # Lengths of the holes\n\n# Model\nmodel = Model([\n sum(holes) == total_length\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"holes\": holes.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["holes"]} +{"id": "hakan_examples__facility_location", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/facility_location_problem.py"], "description": "A company is considering opening warehouses in four cities to meet regional demands at minimal costs. The potential cities for these warehouses are New York, Los Angeles, Chicago, and Atlanta. The company needs to decide which warehouses to open based on several constraints: 1. If the New York warehouse is opened, then the Los Angeles warehouse must also be opened. 2. No more than three warehouses can be operational in any given week. 3. Either the Atlanta or the Los Angeles warehouse must be opened. The objective is to determine the optimal set of warehouses to open and the distribution of shipments to various regions to minimize total costs. Print the total cost (total_cost), whether the warehouses are open (open_warehouse), and the shipping details for each region per warehouse (ships).", "input_data": "warehouse_s = [\"New York\", \"Los Angeles\", \"Chicago\", \"Atlanta\"] fixed_costs = [400, 500, 300, 150] # Weekly fixed costs per warehouse max_shipping = 100 # Max units per week per warehouse demands = [80, 70, 40] # Weekly demands for regions 1 to 3 shipping_costs = [ [20, 40, 50], # New York to regions 1, 2, 3 [48, 15, 26], # Los Angeles to regions 1, 2, 3 [26, 35, 18], # Chicago to regions 1, 2, 3 [24, 50, 35] # Atlanta to regions 1, 2, 3 ]", "model": "# Data\nwarehouse_s = [\"New York\", \"Los Angeles\", \"Chicago\", \"Atlanta\"]\nfixed_costs = [400, 500, 300, 150] # Weekly fixed costs per warehouse\nmax_shipping = 100 # Max units per week per warehouse\ndemands = [80, 70, 40] # Weekly demands for regions 1 to 3\nshipping_costs = [\n [20, 40, 50], # New York to regions 1, 2, 3\n [48, 15, 26], # Los Angeles to regions 1, 2, 3\n [26, 35, 18], # Chicago to regions 1, 2, 3\n [24, 50, 35] # Atlanta to regions 1, 2, 3\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nnum_companies = len(warehouse_s)\nnum_regions = len(demands)\nnew_york, los_angeles, chicago, atlanta = range(num_companies)\ncosts = cpm_array(shipping_costs)\n\n# Decision Variables\nopen_warehouse = boolvar(shape=num_companies, name=\"open_warehouse\") # 1 if the warehouse is open, 0 otherwise\nships = intvar(0, max_shipping, shape=(num_companies, num_regions), name=\"ships\") # what to ship to each region\ntotal_cost = intvar(0, 10000, name=\"total_cost\") # total cost of shipping\n\n# Model\nmodel = Model()\n\n# each warehouse can only send max 100 units per week\nfor i in range(num_companies):\n model += [sum([open_warehouse[i] * ships[i, j] for j in range(num_regions)]) <= max_shipping]\n\n# the demands of the regions\nfor j in range(num_regions):\n model += [sum([open_warehouse[i] * ships[i, j] for i in range(num_companies)]) >= demands[j]]\n\n# connect open with ships\nfor i in range(num_companies):\n model += [open_warehouse[i].implies(sum([ships[i, j] for j in range(num_regions)]) > 0)]\n\n# total cost\nmodel += [total_cost == sum([open_warehouse[i] *\n (fixed_costs[i] + sum([ships[i, j] * costs[i, j] for j in range(num_regions)]))\n for i in range(num_companies)])]\n\n# 1. If the New York warehouse is opened, then the Los Angeles warehouse must be opened.\nmodel += [open_warehouse[new_york].implies(open_warehouse[los_angeles])]\n\n# 2. At most three warehouses can be opened.\nmodel += [sum(open_warehouse) <= 3]\n\n# 3. Either the Atlanta or the Los Angeles warehouse must be opened.\nmodel += [open_warehouse[atlanta] | open_warehouse[los_angeles]]\n\n# Objective: Minimize total cost\nmodel.minimize(total_cost)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"total_cost\": total_cost.value(),\n \"open_warehouse\": open_warehouse.value().tolist(),\n \"ships\": ships.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["total_cost", "ships", "open_warehouse"]} +{"id": "hakan_examples__fifty_puzzle", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/50_puzzle.py", "# Source description: http://www.chlond.demon.co.uk/puzzles/puzzles1.html, puzzle nr. 5."], "description": "A side show at Coney Island is described as follows: \"There were ten little dummies which you were to knock over with baseballs. The man said: 'Take as many throws as you like at a cent apiece and stand as close as you please. Add up the numbers on all the men that you knock down and when the sum amounts to exactly fifty, neither more nor less you get a genuine 25 cent Maggie Cline cigar with a gold band around it.'\" The numbers on the ten dummies were 15, 9, 30, 21, 19, 3, 12, 6, 25, 27. Print the dummies that are knocked over (dummies).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\ntarget_sum = 50 # Target sum to achieve\nvalues = [15, 9, 30, 21, 19, 3, 12, 6, 25, 27] # Numbers on the dummies\nn = len(values)\n\n# Decision variables\ndummies = boolvar(shape=n, name=\"dummies\") # Boolean array to indicate which dummies are knocked over\n\n# Model\nmodel = Model([\n sum([values[i] * dummies[i] for i in range(n)]) == target_sum\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"dummies\": dummies.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["dummies"]} +{"id": "hakan_examples__three_sum", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/3sum.py"], "description": "Given a collection of integers, find three elements that sum to zero. Print whether each element is selected (indices).", "input_data": "nums = [-1, 6, 8, 9, 10, -100, 78, 0, 1] # Collection of integers", "model": "# Data\nnums = [-1, 6, 8, 9, 10, -100, 78, 0, 1] # Collection of integers\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = len(nums)\nm = 3 # The number of elements that should sum to 0\n\n# Decision variables\nindices = boolvar(shape=n, name=\"indices\") # Boolean array to indicate which elements are selected\n\n# Model\nmodel = Model([\n sum([nums[i] * indices[i] for i in range(n)]) == 0,\n sum(indices) == m\n])\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"indices\": indices.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["indices"]} +{"id": "hakan_examples__twelve_pack", "category": "hakan_examples", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/12_pack_problem.py"], "description": "Given a target number of beers, find the closest combination of 7-packs and 13-packs that meets or exceeds the target. Print the counts of 7-packs and 13-packs used (counts).", "input_data": "target = 20 # Target number of beers", "model": "# Data\ntarget = 20 # Target number of beers\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nimport builtins\n\n# Parameters\nn = 2 # Number of pack sizes\npacks = [7, 13] # Pack sizes\nmax_val = target * 2 # Arbitrary max limit of pack counts\n\n# Decision variables\ncounts = intvar(0, max_val, shape=n, name=\"counts\") # Count of each pack size used\ntotal = intvar(0, max_val * n, name=\"total\") # Total number of beers\n\n# Model\nmodel = Model([\n total == (counts * packs).sum(),\n total >= target,\n])\n\n# Objective\nmodel.minimize(total)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"counts\": counts.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["counts"]} +{"id": "cpmpy_examples__bus_scheduling", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/bus_schedule.py", "# Source description: Problem from Taha \"Introduction to Operations Research\", page 58."], "description": "Progress City is considering a mass-transit bus system to reduce in-city driving. The goal is to determine the minimum number of buses required to meet the transportation needs throughout the day. The demand for buses is approximated as constant over successive 4-hour intervals. Each bus can operate only 8 successive hours a day. We need to ensure that the number of buses available in each 4-hour interval meets the demand for that interval. Also, due to overlapping shifts, the schedule must account for buses transitioning between intervals. Print the number of buses scheduled in each time slot (x).", "input_data": "demands = [4, 8, 10, 7, 12, 4] # Demand for buses in each 4-hour time slot", "model": "# Data\ndemands = [4, 8, 10, 7, 12, 4] # Demand for buses in each 4-hour time slot\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nslots = len(demands)\n\n# Decision Variables\n# x[i] represents the number of buses scheduled to start working in the i-th 4-hour slot\nx = intvar(0, sum(demands), shape=slots, name=\"x\")\n\n# Model the constraints\n# Each bus operates for 8 hours, so it covers two consecutive 4-hour slots\nconstraints = []\nfor i in range(slots):\n # The number of buses covering the i-th and (i+1)-th slot should meet the demand of the (i+1)-th slot\n constraints.append(x[i] + x[(i + 1) % slots] >= demands[(i + 1) % slots])\n\n# Create the model with constraints\nmodel = Model(constraints)\n\n# Objective: Minimize the total number of buses used\nmodel.minimize(sum(x))\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"id": "cpmpy_examples__jobshop", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/jobshop.py", "# Source description: https://developers.google.com/optimization/scheduling/job_shop"], "description": "Job Shop Scheduling Problem One common scheduling problem is the job shop, in which multiple jobs are processed on several machines. Each job consists of a sequence of tasks, which must be performed in a given order, and each task must be processed on a specific machine. For example, the job could be the manufacture of a single consumer item, such as an automobile. The problem is to schedule the tasks on the machines so as to minimize the length of the schedule—the time it takes for all the jobs to be completed. There are several constraints for the job shop problem: - No task for a job can be started until the previous task for that job is completed. - A machine can only work on one task at a time. - A task, once started, must run to completion. Print the optimal makespan (makespan), which is the total time taken to complete all jobs.", "input_data": "jobs_data = [ # (job_id, task_id) -> (machine_id, duration) [(0, 3), (1, 2), (2, 2)], # Job 0 [(0, 2), (2, 1), (1, 4)], # Job 1 [(1, 4), (2, 3)] # Job 2 ]", "model": "# Data\njobs_data = [ # (job_id, task_id) -> (machine_id, duration)\n [(0, 3), (1, 2), (2, 2)], # Job 0\n [(0, 2), (2, 1), (1, 4)], # Job 1\n [(1, 4), (2, 3)] # Job 2\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nfrom itertools import combinations\nimport builtins # To access the original built-in functions (because of the import * above)\n\n# Extract job data\nn_jobs = len(jobs_data)\nn_tasks = builtins.sum(len(job) for job in jobs_data)\nmachines = set(task[0] for job in jobs_data for task in job)\nn_machines = len(machines)\n\n# Create variables for start and end times\nmax_duration = builtins.sum(task[1] for job in jobs_data for task in job)\nmax_tasks_per_job = builtins.max(len(job) for job in jobs_data)\nstart_times = intvar(0, max_duration, shape=(n_jobs, max_tasks_per_job), name=\"start_times\")\nend_times = intvar(0, max_duration, shape=(n_jobs, max_tasks_per_job), name=\"end_times\")\nmakespan = intvar(0, max_duration, name=\"makespan\")\n\n# Create the model\nmodel = Model()\n\n# Add constraints for each task\nfor job_id, job in enumerate(jobs_data):\n for task_id, (machine, duration) in enumerate(job):\n model += (end_times[job_id, task_id] == start_times[job_id, task_id] + duration)\n\n # No task can start before the previous one ends\n if task_id > 0:\n model += (start_times[job_id, task_id] >= end_times[job_id, task_id - 1])\n\n# Add machine constraints\nfor machine in machines:\n machine_tasks = [(job_id, task_id) for job_id, job in enumerate(jobs_data) for task_id, (m, duration) in enumerate(job) if m == machine]\n for (job1, task1), (job2, task2) in combinations(machine_tasks, 2):\n model += (start_times[job1, task1] >= end_times[job2, task2]) | (start_times[job2, task2] >= end_times[job1, task1])\n\n# Objective: Minimize makespan\nmodel += (makespan == max(end_times.flatten()))\nmodel.minimize(makespan)\n\n# Solve the model\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"makespan\": makespan.value()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["makespan"]} +{"id": "cpmpy_examples__minesweeper", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/minesweeper.py", "# Source description: https://minesweeper.online"], "description": "Minesweeper rules are very simple. The board is divided into cells, with mines randomly distributed. To win, you need to open all the cells. The number on a cell shows the number of mines adjacent to it. Using this information, you can determine cells that are safe, and cells that contain mines. Cells suspected of being mines can be marked with a flag using the right mouse button. The task is to determine which 'X' fields contain mines based on the provided numerical clues. Print whether each cell is a mine or not (mines).", "input_data": "X = -1 game_data = [ # 0-8: number of mines around, -1: not opened [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] ]", "model": "# Data\nX = -1\ngame_data = [ # 0-8: number of mines around, -1: not opened\n [2, 3, X, 2, 2, X, 2, 1],\n [X, X, 4, X, X, 4, X, 2],\n [X, X, X, X, X, X, 4, X],\n [X, 5, X, 6, X, X, X, 2],\n [2, X, X, X, 5, 5, X, 2],\n [1, 3, 4, X, X, X, 4, X],\n [0, 1, X, 4, X, X, X, 3],\n [0, 1, 2, X, 2, 3, X, 2]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Parameters\ngame = np.array(game_data)\nrows, cols = game.shape\nS = [-1, 0, 1] # for the neighbors of a cell\n\n# Decision Variables\nmines = boolvar(shape=game.shape) # True: mine, False: not mine\n\nmodel = Model()\nfor (r, c), val in np.ndenumerate(game):\n if val != X:\n # This cell cannot be a mine\n model += mines[r, c] == 0\n # Count neighbors\n model += (sum(mines[r + a, c + b]\n for a in S for b in S\n if 0 <= r + a < rows and 0 <= c + b < cols and (a, b) != (0, 0))\n == val)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"mines\": mines.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["mines"]} +{"id": "cpmpy_examples__packing_rectangles", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/packing_rectangles.ipynb", "# Source Description: https://github.com/Alexander-Schiendorfer/cp-examples/tree/main/packing"], "description": "The rectangular packing problem involves placing a set of rectangular items into a larger rectangular area such that no items overlap and all items are within the boundaries of the larger area. The objective is to minimize the total area of the larger rectangle required to pack all the items. Given the widths and heights of the items, determine their positions within the larger rectangle while ensuring no overlap and minimizing the total area. Print the positions of the items (pos_x, pos_y) and the dimensions of the larger rectangle (total_x, total_y).", "input_data": "widths = [3, 4, 2, 1] # Widths of the items heights = [2, 3, 1, 4] # Heights of the items", "model": "# Data\nwidths = [3, 4, 2, 1] # Widths of the items\nheights = [2, 3, 1, 4] # Heights of the items\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nfrom cpmpy.expressions.utils import all_pairs\n\n\ndef model_packing_rectangular(widths, heights):\n # Number of different items\n n = len(widths)\n\n # max dimensions of the whole area\n area_min_x, area_max_x = max(widths), sum(widths)\n area_min_y, area_max_y = max(heights), sum(heights)\n\n # Decision variables\n pos_x = intvar(0, area_max_x, shape=n)\n pos_y = intvar(0, area_max_y, shape=n)\n\n total_x = intvar(area_min_x, area_max_x)\n total_y = intvar(area_min_y, area_max_y)\n\n m = Model()\n\n ## Necessary constraints\n # Every item has to be within the overall area\n m += [pos_x + widths <= total_x,\n pos_y + heights <= total_y]\n\n # No-overlap: every item has to be fully above, below or next to every other item\n for i, j in all_pairs(range(n)):\n m += ((pos_x[i] + widths[i] <= pos_x[j]) |\n (pos_x[j] + widths[j] <= pos_x[i]) |\n (pos_y[i] + heights[i] <= pos_y[j]) |\n (pos_y[j] + heights[j] <= pos_y[i]))\n\n # Minimize wrt the overall area\n m.minimize(total_x * total_y)\n\n ## Optional constraints\n # The needed space needs to be wider than taller\n # m += (total_x > total_y),\n\n # The needed space has to have a width larger than 10\n # m += (total_x >= 10),\n\n # The needed space has to have a height larger than 10\n # m += (total_y >= 10)\n\n return m, (pos_x, pos_y, total_x, total_y)\n\n\n# Example usage\nmodel, (pos_x, pos_y, total_x, total_y) = model_packing_rectangular(widths, heights)\nmodel.solve()\n\n# Print\nsolution = {\n \"pos_x\": pos_x.value().tolist(),\n \"pos_y\": pos_y.value().tolist(),\n \"total_x\": total_x.value(),\n \"total_y\": total_y.value()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["total_y", "pos_x", "pos_y", "total_x"]} +{"id": "cpmpy_examples__resource_constrained_project_scheduling", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/rcpsp.py", "# Description: https://python-mip.readthedocs.io/en/latest/examples.html#resource-constrained-project-scheduling"], "description": "The resource-constrained project scheduling problem involves scheduling a set of jobs, each with a specific duration and resource requirement, such that the total project duration (makespan) is minimized. Each job may have precedence constraints, meaning certain jobs must be completed before others can start. Additionally, there are multiple types of resources, each with a limited capacity that must not be exceeded at any time. Given the durations of the jobs, their resource requirements, the capacities of the resources, and the precedence constraints between the jobs, determine the start times of the jobs that minimize the makespan while satisfying all constraints. Print the start times of the jobs (start_time).", "input_data": "durations_data = [0, 3, 2, 5, 4, 2, 3, 4, 2, 4, 6, 0] resource_needs_data = [[0, 0], [5, 1], [0, 4], [1, 4], [1, 3], [3, 2], [3, 1], [2, 4], [4, 0], [5, 2], [2, 5], [0, 0]] resource_capacities_data = [6, 8] successors_link_data = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 9], [2, 10], [3, 8], [4, 6], [4, 7], [5, 9], [5, 10], [6, 8], [6, 9], [7, 8], [8, 11], [9, 11], [10, 11]]", "model": "# Data\ndurations_data = [0, 3, 2, 5, 4, 2, 3, 4, 2, 4, 6, 0]\nresource_needs_data = [[0, 0], [5, 1], [0, 4], [1, 4], [1, 3], [3, 2], [3, 1], [2, 4], [4, 0], [5, 2], [2, 5], [0, 0]]\nresource_capacities_data = [6, 8]\nsuccessors_link_data = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 9], [2, 10], [3, 8], [4, 6], [4, 7], [5, 9], [5, 10], [6, 8], [6, 9], [7, 8], [8, 11], [9, 11], [10, 11]]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Parameters\ndurations = np.array(durations_data)\nresource_needs = np.array(resource_needs_data)\nresource_capacities = np.array(resource_capacities_data)\nsuccessors_link = np.array(successors_link_data)\n\nnb_resource = len(resource_capacities)\nnb_jobs = len(durations)\nmax_duration = sum(durations) # dummy upper bound, can be improved of course\n\n# Decision Variables\nstart_time = intvar(0, max_duration, shape=nb_jobs) # start time of each job\n\nmodel = Model()\n\n# Precedence constraints\nfor j in range(successors_link.shape[0]):\n model += start_time[successors_link[j, 1]] >= start_time[successors_link[j, 0]]+durations[successors_link[j, 0]]\n\n# Cumulative resource constraint\nfor r in range(nb_resource):\n model += Cumulative(start=start_time, duration=durations, end=start_time+durations,\n demand=resource_needs[:, r], capacity=resource_capacities[r])\n\nmakespan = max(start_time)\nmodel.minimize(makespan)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"start_time\": start_time.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["start_time"]} +{"id": "cpmpy_examples__room_assignment", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/room_assignment.ipynb"], "description": "The room assignment problem involves assigning a set of requests to a limited number of rooms such that each request is assigned to one room for its entire duration. Some requests may already have a room pre-assigned. The main constraint is that a room can only serve one request at a time, meaning no overlapping requests can be assigned to the same room. Print the room assignments for the requests (room_assignments).", "input_data": "max_rooms = 5 # Maximum number of rooms available start_data = [\"2024-05-01\", \"2024-05-02\", \"2024-05-03\", \"2024-05-04\"] # Start date of the requests end_data = [\"2024-05-05\", \"2024-05-06\", \"2024-05-07\", \"2024-05-08\"] # End date of the requests preassigned_room_data = [3, -1, -1, -1] # Room 3 pre-assigned for the first request, -1 for no pre-assignment. So, the second, third, and fourth requests have no pre-assigned rooms.", "model": "# Data\nmax_rooms = 5 # Maximum number of rooms available\nstart_data = [\"2024-05-01\", \"2024-05-02\", \"2024-05-03\", \"2024-05-04\"] # Start date of the requests\nend_data = [\"2024-05-05\", \"2024-05-06\", \"2024-05-07\", \"2024-05-08\"] # End date of the requests\npreassigned_room_data = [3, -1, -1, -1] # Room 3 pre-assigned for the first request, -1 for no pre-assignment. So, the second, third, and fourth requests have no pre-assigned rooms.\n# End of data\n\n# Import libraries\nimport pandas as pd\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Parameters\ndata = {\n \"start\": pd.to_datetime(start_data),\n \"end\": pd.to_datetime(end_data),\n # convert 0 to NaN\n \"room\": [r if r != -1 else np.nan for r in preassigned_room_data]\n}\ndf = pd.DataFrame(data)\n\n\ndef model_rooms(df, max_rooms):\n n_requests = len(df)\n\n # All requests must be assigned to one out of the rooms (same room during entire period).\n requestvars = intvar(0, max_rooms - 1, shape=(n_requests,))\n\n m = Model()\n\n # Some requests already have a room pre-assigned\n for idx, row in df.iterrows():\n if not pd.isna(row['room']):\n m += (requestvars[idx] == int(row['room']))\n\n # A room can only serve one request at a time.\n # <=> requests on the same day must be in different rooms\n for day in pd.date_range(min(df['start']), max(df['end'])):\n overlapping = df[(df['start'] <= day) & (day < df['end'])]\n if len(overlapping) > 1:\n m += AllDifferent(requestvars[overlapping.index])\n\n return m, requestvars\n\n\n# Example usage\nmodel, room_assignments = model_rooms(df, max_rooms)\nmodel.solve()\n\n# Print\nsolution = {\"room_assignments\": room_assignments.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["room_assignments"]} +{"id": "cpmpy_examples__send_more_money", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/send_more_money.py"], "description": "Send More Money Puzzle The \"Send More Money\" puzzle is a classic cryptarithmetic problem where each letter represents a unique digit. The goal is to assign digits to the letters such that the following equation holds true: SEND + MORE ------ MONEY Each letter must be assigned a unique digit from 0 to 9, and the first letter of each word cannot be zero. Print the values assigned to each letter (s, e, n, d, m, o, r, y).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Decision variables\ns, e, n, d, m, o, r, y = intvar(0, 9, shape=8)\n\nmodel = Model(\n AllDifferent([s, e, n, d, m, o, r, y]),\n (sum([s, e, n, d] * np.array([1000, 100, 10, 1])) \\\n + sum([m, o, r, e] * np.array([1000, 100, 10, 1])) \\\n == sum([m, o, n, e, y] * np.array([10000, 1000, 100, 10, 1]))),\n s > 0,\n m > 0,\n)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"s\": s.value(),\n \"e\": e.value(),\n \"n\": n.value(),\n \"d\": d.value(),\n \"m\": m.value(),\n \"o\": o.value(),\n \"r\": r.value(),\n \"y\": y.value()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["y", "e", "s", "r", "o", "d", "m", "n"]} +{"id": "cpmpy_examples__set_game", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/set_game.ipynb", "# Description: https://en.wikipedia.org/wiki/Set_(card_game)"], "description": "Set (stylized as SET or SET!) is a real-time card game designed by Marsha Falco in 1974 and published by Set Enterprises in 1991. The deck consists of 81 unique cards that vary in four features across three possibilities for each kind of feature: number of shapes (one, two, or three), shape (diamond, squiggle, oval), shading (solid, striped, or open), and color (red, green, or purple).[2] Each possible combination of features (e.g. a card with three striped green diamonds) appears as a card precisely once in the deck. In the game, certain combinations of three cards are said to make up a \"set\". For each one of the four categories of features—color, number, shape, and shading—the three cards must display that feature as either a) all the same, or b) all different. Put another way: For each feature the three cards must avoid having two cards showing one version of the feature and the remaining card showing a different version. For example, 3 solid red diamonds, 2 solid green squiggles, and 1 solid purple oval form a set, because the shadings of the three cards are all the same, while the numbers, the colors, and the shapes among the three cards are all different. For any set, the number of features that are constant (the same on all three cards) and the number of features that differ (different on all three cards) may break down as: all 4 features differing; or 1 feature being constant and 3 differing; or 2 constant and 2 differing; or 3 constant and 1 differing. (All 4 features being constant would imply that the three cards in the set are identical, which is impossible since no cards in the Set deck are identical.) Print the indices of the winning set of cards (winning_cards).", "input_data": "# Constants numbers = ONE, TWO, THREE = 1, 2, 3 colors = RED, PURPLE, GREEN = 1, 2, 3 shapes = DIAMOND, RECT, ELLIPSE = 1, 2, 3 fills = FULL, EMPTY, STRIPED = 1, 2, 3 # Make the card deck cards_data = [ [ONE, EMPTY, GREEN, DIAMOND], [TWO, STRIPED, RED, RECT], [THREE, STRIPED, GREEN, DIAMOND], [THREE, FULL, RED, DIAMOND], [ONE, STRIPED, GREEN, DIAMOND], [ONE, EMPTY, RED, DIAMOND], [TWO, FULL, PURPLE, DIAMOND], [THREE, FULL, PURPLE, ELLIPSE], [THREE, FULL, GREEN, RECT], [ONE, FULL, PURPLE, DIAMOND], [ONE, STRIPED, PURPLE, DIAMOND], [ONE, FULL, GREEN, RECT] ]", "model": "# Data\n# Constants\nnumbers = ONE, TWO, THREE = 1, 2, 3\ncolors = RED, PURPLE, GREEN = 1, 2, 3\nshapes = DIAMOND, RECT, ELLIPSE = 1, 2, 3\nfills = FULL, EMPTY, STRIPED = 1, 2, 3\n\n# Make the card deck\ncards_data = [\n [ONE, EMPTY, GREEN, DIAMOND],\n [TWO, STRIPED, RED, RECT],\n [THREE, STRIPED, GREEN, DIAMOND],\n [THREE, FULL, RED, DIAMOND],\n [ONE, STRIPED, GREEN, DIAMOND],\n [ONE, EMPTY, RED, DIAMOND],\n [TWO, FULL, PURPLE, DIAMOND],\n [THREE, FULL, PURPLE, ELLIPSE],\n [THREE, FULL, GREEN, RECT],\n [ONE, FULL, PURPLE, DIAMOND],\n [ONE, STRIPED, PURPLE, DIAMOND],\n [ONE, FULL, GREEN, RECT]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\ncards = cpm_array(cards_data)\ngiven_numbers, given_fills, given_colors, given_shapes = cards[:, 0], cards[:, 1], cards[:, 2], cards[:, 3]\n\n# decision variables\nn_cards = len(cards)\nwinning_cards = intvar(0, n_cards - 1, shape=3, name=\"winning\") # indices of the winning cards\nc1, c2, c3 = winning_cards\n\n# constraints\nmodel = Model()\nmodel += AllDifferent(winning_cards)\n\n# numbers must be all equal or all different\nwinning_nbs = [given_numbers[c1], given_numbers[c2], given_numbers[c3]]\nmodel += AllEqual(winning_nbs) | AllDifferent(winning_nbs)\n\n# filling pattern must be all equal or all different\nwinning_fills = [given_fills[c1], given_fills[c2], given_fills[c3]]\nmodel += AllEqual(winning_fills) | AllDifferent(winning_fills)\n\n# colors must be all equal or all different\nwinning_colors = [given_colors[c1], given_colors[c2], given_colors[c3]]\nmodel += AllEqual(winning_colors) | AllDifferent(winning_colors)\n\n# shapes must be all equal or all different\nwinning_shapes = [given_shapes[c1], given_shapes[c2], given_shapes[c3]]\nmodel += AllEqual(winning_shapes) | AllDifferent(winning_shapes)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"winning_cards\": winning_cards.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["winning_cards"]} +{"id": "cpmpy_examples__sudoku", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/sudoku.py", "# Source description: sudoku.com"], "description": "The goal of Sudoku is to fill a 9x9 grid with numbers so that each row, column and 3x3 section contain all the digits between 1 and 9. Input is a grid with some cells filled with numbers and some empty. Print the solved grid (grid).", "input_data": "input_grid = [ # 0 represents empty cells [0, 0, 0, 2, 0, 5, 0, 0, 0], [0, 9, 0, 0, 0, 0, 7, 3, 0], [0, 0, 2, 0, 0, 9, 0, 6, 0], [2, 0, 0, 0, 0, 0, 4, 0, 9], [0, 0, 0, 0, 7, 0, 0, 0, 0], [6, 0, 9, 0, 0, 0, 0, 0, 1], [0, 8, 0, 4, 0, 0, 1, 0, 0], [0, 6, 3, 0, 0, 0, 0, 8, 0], [0, 0, 0, 6, 0, 8, 0, 0, 0]]", "model": "# Data\ninput_grid = [ # 0 represents empty cells\n [0, 0, 0, 2, 0, 5, 0, 0, 0],\n [0, 9, 0, 0, 0, 0, 7, 3, 0],\n [0, 0, 2, 0, 0, 9, 0, 6, 0],\n\n [2, 0, 0, 0, 0, 0, 4, 0, 9],\n [0, 0, 0, 0, 7, 0, 0, 0, 0],\n [6, 0, 9, 0, 0, 0, 0, 0, 1],\n\n [0, 8, 0, 4, 0, 0, 1, 0, 0],\n [0, 6, 3, 0, 0, 0, 0, 8, 0],\n [0, 0, 0, 6, 0, 8, 0, 0, 0]]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\nimport numpy as np\n\n# Parameters\ne = 0 # value for empty cells\ngiven = np.array(input_grid) # numpy array for easy indexing\n\n# Decision Variables\ngrid = intvar(1, 9, shape=given.shape, name=\"grid\")\n\n# Model\nmodel = Model(\n # Constraints on given cells (non-empty)\n grid[given != e] == given[given != e], # numpy's indexing, vectorized equality\n # Constraints on rows and columns\n [AllDifferent(row) for row in grid],\n [AllDifferent(col) for col in grid.T], # numpy's transpose\n)\n\n# Constraints on blocks\nfor i in range(0, 9, 3):\n for j in range(0, 9, 3):\n model += AllDifferent(grid[i:i+3, j:j+3]) # python's indexing\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"grid\": grid.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["grid"]} +{"id": "cpmpy_examples__who_killed_agatha", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/who_killed_agatha.py", "# Source description: http://www.hakank.org/constraint_programming_blog/2014/11/decision_management_community_november_2014_challenge_who_killed_agath.html"], "description": "Someone in Dreadsbury Mansion killed Aunt Agatha. Agatha, the butler, and Charles live in Dreadsbury Mansion, and are the only ones to live there. A killer always hates, and is no richer than his victim. Charles hates noone that Agatha hates. Agatha hates everybody except the butler. The butler hates everyone not richer than Aunt Agatha. The butler hates everyone whom Agatha hates. Noone hates everyone. Who killed Agatha? Print the index of the killer (killer).", "input_data": "names = [\"Agatha herself\", \"the butler\", \"Charles\"]", "model": "# Data\nnames = [\"Agatha herself\", \"the butler\", \"Charles\"]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Agatha, the butler, and Charles live in Dreadsbury Mansion, and\n# are the only ones to live there.\nn = 3\n(agatha, butler, charles) = range(n) # enum constants\n\n# Who killed agatha?\nvictim = agatha\nkiller = intvar(0, n - 1, name=\"killer\") # 0=Agatha, 1=butler, 2=Charles\n\nhates = boolvar(shape=(n, n), name=\"hates\")\nricher = boolvar(shape=(n, n), name=\"richer\")\n\nmodel = Model(\n # A killer always hates, and is no richer than, his victim.\n # note; 'killer' is a variable, so must write ==1/==0 explicitly\n hates[killer, victim] == 1,\n richer[killer, victim] == 0,\n\n # implied richness: no one richer than himself, and anti-reflexive\n [~richer[i, i] for i in range(n)],\n [(richer[i, j]) == (~richer[j, i]) for i in range(n) for j in range(i + 1, n)],\n\n # Charles hates noone that Agatha hates.\n [(hates[agatha, i]).implies(~hates[charles, i]) for i in range(n)],\n\n # Agatha hates everybody except the butler.\n hates[agatha, (agatha, charles, butler)] == [1, 1, 0],\n\n # The butler hates everyone not richer than Aunt Agatha.\n [(~richer[i, agatha]).implies(hates[butler, i]) for i in range(n)],\n\n # The butler hates everyone whom Agatha hates.\n [(hates[agatha, i]).implies(hates[butler, i]) for i in range(n)],\n\n # Noone hates everyone.\n [sum(hates[i, :]) <= 2 for i in range(n)],\n)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"killer\": killer.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["killer"]} +{"id": "cpmpy_examples__wolf_goat_cabbage", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/wolf_goat_cabbage.py", "# Description: https://en.wikipedia.org/wiki/Wolf,_goat_and_cabbage_problem"], "description": "The wolf, goat and cabbage problem is a river crossing puzzle. It dates back to at least the 9th century, and has entered the folklore of several cultures. The story: A farmer with a wolf, a goat, and a cabbage must cross a river by boat. The boat can carry only the farmer and a single item. If left unattended together, the wolf would eat the goat, or the goat would eat the cabbage. How can they cross the river without anything being eaten? Print whether the wolf, goat, cabbage, and boat are on the destination shore (1) or the starting shore (0) at each stage (wolf_pos, goat_pos, cabbage_pos, boat_pos).", "input_data": "stage = 8 # Number of stages", "model": "# Data\nstage = 8 # Number of stages\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\nwolf_pos = boolvar(stage)\ncabbage_pos = boolvar(stage)\ngoat_pos = boolvar(stage)\nboat_pos = boolvar(stage)\n\nmodel = Model(\n # Initial situation\n (boat_pos[0] == 0),\n (wolf_pos[0] == 0),\n (goat_pos[0] == 0),\n (cabbage_pos[0] == 0),\n\n # Boat keeps moving between shores\n [boat_pos[i] != boat_pos[i - 1] for i in range(1, stage)],\n\n # Final situation\n (boat_pos[-1] == 1),\n (wolf_pos[-1] == 1),\n (goat_pos[-1] == 1),\n (cabbage_pos[-1] == 1),\n\n # # Wolf and goat cannot be left alone\n [(goat_pos[i] != wolf_pos[i]) | (boat_pos[i] == wolf_pos[i]) for i in range(stage)],\n\n # # Goat and cabbage cannot be left alone\n [(goat_pos[i] != cabbage_pos[i]) | (boat_pos[i] == goat_pos[i]) for i in range(stage)],\n\n # # Only one animal/cabbage can move per turn\n [abs(wolf_pos[i] - wolf_pos[i + 1]) + abs(goat_pos[i] - goat_pos[i + 1]) + abs(\n cabbage_pos[i] - cabbage_pos[i + 1]) <= 1 for i in range(stage - 1)],\n)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"wolf_pos\": wolf_pos.value().tolist(), \"goat_pos\": goat_pos.value().tolist(),\n \"cabbage_pos\": cabbage_pos.value().tolist(), \"boat_pos\": boat_pos.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["boat_pos", "0", "cabbage_pos", "goat_pos", "wolf_pos", "1"]} +{"id": "cpmpy_examples__zebra", "category": "cpmpy_examples", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/zebra.py", "# Description: https://en.wikipedia.org/wiki/Wolf,_goat_and_cabbage_problem", "# Misc: Based on PyCSP3's Zebra.py by C. Lecoutre, https://github.com/xcsp3team/pycsp3/blob/master/problems/csp/single/Zebra.py"], "description": "The Zebra puzzle (sometimes referred to as Einstein's puzzle) is defined as follows. There are five houses in a row, numbered from left to right. Each of the five houses is painted a different color, and has one inhabitant. The inhabitants are all of different nationalities, own different pets, drink different beverages and have different jobs. We know that: - colors are yellow, green, red, white, and blue - nations of inhabitants are italy, spain, japan, england, and norway - pets are cat, zebra, bear, snails, and horse - drinks are milk, water, tea, coffee, and juice - jobs are painter, sculptor, diplomat, pianist, and doctor - the painter owns the horse - the diplomat drinks coffee - the one who drinks milk lives in the white house - the Spaniard is a painter - the Englishman lives in the red house - the snails are owned by the sculptor - the green house is on the left of the red one - the Norwegian lives on the right of the blue house - the doctor drinks milk - the diplomat is Japanese - the Norwegian owns the zebra - the green house is next to the white one - the horse is owned by the neighbor of the diplomat - the Italian either lives in the red, white or green house Print the numbers representing the house of each inhabitant (colors, nations, jobs, pets, drinks). The same number represents the same house.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\nn_houses = 5\n\n# colors[i] is the house of the ith color\nyellow, green, red, white, blue = colors = intvar(0,n_houses-1, shape=n_houses)\n\n# nations[i] is the house of the inhabitant with the ith nationality\nitaly, spain, japan, england, norway = nations = intvar(0,n_houses-1, shape=n_houses)\n\n# jobs[i] is the house of the inhabitant with the ith job\npainter, sculptor, diplomat, pianist, doctor = jobs = intvar(0,n_houses-1, shape=n_houses)\n\n# pets[i] is the house of the inhabitant with the ith pet\ncat, zebra, bear, snails, horse = pets = intvar(0,n_houses-1, shape=n_houses)\n\n# drinks[i] is the house of the inhabitant with the ith preferred drink\nmilk, water, tea, coffee, juice = drinks = intvar(0,n_houses-1, shape=n_houses)\n\nmodel = Model(\n AllDifferent(colors),\n AllDifferent(nations),\n AllDifferent(jobs),\n AllDifferent(pets),\n AllDifferent(drinks),\n\n painter == horse,\n diplomat == coffee,\n white == milk,\n spain == painter,\n england == red,\n snails == sculptor,\n green + 1 == red,\n blue + 1 == norway,\n doctor == milk,\n japan == diplomat,\n norway == zebra,\n abs(green - white) == 1,\n #horse in {diplomat - 1, diplomat + 1},\n (horse == diplomat-1)|(horse == diplomat+1),\n #italy in {red, white, green}\n (italy == red)|(italy == white)|(italy == green),\n)\nmodel.solve()\n\n# Print\nsolution = {\n \"colors\": colors.value().tolist(),\n \"nations\": nations.value().tolist(),\n \"jobs\": jobs.value().tolist(),\n \"pets\": pets.value().tolist(),\n \"drinks\": drinks.value().tolist(),\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["colors", "jobs", "nations", "pets", "drinks"]} +{"id": "aplai_course__1_bank_card", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/bank_card.mzn"], "description": "My bank card has a 4 digit pin, abcd. I use the following facts to help me remember it: - no two digits are the same - the 2-digit number cd is 3 times the 2-digit number ab - the 2-digit number da is 2 times the 2-digit number bc Print the PIN (a, b, c, d).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision Variables\na, b, c, d = intvar(1, 9, shape=4) # a, b, c, d are the four digits of the PIN\n\n# Constraints\nmodel = Model()\n\nmodel += AllDifferent([a, b, c, d]) # no two digits are the same\nmodel += 10 * c + d == 3 * (10 * a + b) # cd is 3 times ab\nmodel += 10 * d + a == 2 * (10 * b + c) # da is 2 times bc\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"a\": a.value(), \"b\": b.value(), \"c\": c.value(), \"d\": d.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["b", "d", "c", "a"]} +{"id": "aplai_course__5_climbing_stairs", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/climbing_stairs.mzn"], "description": "We want to climb a stair of n steps with [m1, m2] steps at a time. For example a stair of 4 steps with m1 = 1, and m2 = 2 can be climbed with a sequence of four one-step moves or with two two-steps moves. Find a way to climb a stair of 20 steps with m1 = 3 and m2 = 5, i.e. you can take only 3 or 4 or 5 steps at a time. Print the number of steps (steps) taken at each move as a list of 20 integers, where each integer is between 3 and 5, or 0 if no steps are taken at that move, i.e. after we reach the top of the stair with the last move.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\nimport numpy as np\n\n# Parameters\nn = 20 # total number of steps in the stair\nm1, m2 = 3, 5 # number of steps that can be taken at a time\n\n# Decision variables\n# In the worst case, we take all steps one at a time, so we have 'n' decision variables\nsteps = intvar(0, m2, shape=n) # steps taken at each move\n\n# Model setup\nmodel = Model()\n\n# Constraint: the sum of steps should equal the total number of stairs\nmodel += sum(steps) == n\n\n# Constraint: the number of steps taken at each move should be between m1 and m2 or 0\nmodel += [(steps[i] >= m1) | (steps[i] == 0) for i in range(n)]\nmodel += [steps[i] <= m2 for i in range(n)]\n\n# Trailing zeros: If a step is 0, then all the following steps should be 0\nfor i in range(1, n):\n model += (steps[i - 1] == 0).implies(all(steps[j] == 0 for j in range(i, n)))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"steps\": steps.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["steps"]} +{"id": "aplai_course__2_color_simple", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/color_simple.mzn"], "description": "We want to assign a different colour to the following countries: Belgium, Denmark, France, Germany, Netherlands and Luxembourg. Two neighbouring countries cannot have the same colour. You can use integers starting from 1 to represent the colours. Find a colouring that minimizes the number of colours used. Print the colours assigned to each country as a list (colors).", "input_data": "graph = [ # the adjacency of the countries, (i, j) means that country i is adjacent to country j [3, 1], [3, 6], [3, 4], [6, 4], [6, 1], [1, 5], [1, 4], [4, 5], [4, 2] ]", "model": "# Data\ngraph = [ # the adjacency of the countries, (i, j) means that country i is adjacent to country j\n [3, 1],\n [3, 6],\n [3, 4],\n [6, 4],\n [6, 1],\n [1, 5],\n [1, 4],\n [4, 5],\n [4, 2]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\nnum_edges = 9\nnum_nodes = 6\n\n# Decision Variables\ncolors = intvar(1, num_nodes, shape=num_nodes) # the colour assigned to each country\n\n# Constraints\nmodel = Model()\n\n# Two neighbouring countries cannot have the same colour\nfor i, j in graph:\n # Python uses 0-based indexing, but the countries are 1-based, so we need to subtract 1 from the indices\n model += colors[i - 1] != colors[j - 1]\n\n# Objective\n# Find a colouring that minimizes the number of colours used\nmodel.minimize(max(colors))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"colors\": colors.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["colors"]} +{"id": "aplai_course__3_farmer_and_cows", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/farmer_and_cows.mzn"], "description": "A farmer has 25 cows numbered 1 to 25. number 1 cow gives 1kg milk, number 2 gives 2 kg... number and so on up to number 25 that gives 25 kg per day. The farmer has 5 sons and he wants to distribute his cows to them: 7 to the first, 6 to the second and so on down to 3 to the last, however, the total quantity of milk produced should be the same: how can he distribute the cows? Print the assignment of cows to sons (cow_assignments), as a list of 25 integers from 0 to 4.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nnum_cows = 25\nnum_sons = 5\nmilk_per_cow = list(range(1, num_cows + 1))\ncows_per_son = [7, 6, 5, 4, 3]\n\ntotal_milk = sum(milk_per_cow) # Total milk produced by all cows\ntotal_milk_per_son = total_milk // num_sons # Total milk each son should get\n\n# Decision variables\n# Each cow is assigned to a son, represented by 0-4\ncow_assignments = intvar(0, num_sons - 1, shape=num_cows)\n\n# Constraints\nmodel = Model()\n\n# Each son gets a specific number of cows\nfor son in range(num_sons):\n model += sum(cow_assignments == son) == cows_per_son[son]\n\n# The total milk production for each son is equal\nfor son in range(num_sons):\n model += sum(milk_per_cow[i] * (cow_assignments[i] == son) for i in range(num_cows)) == total_milk_per_son\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"cow_assignments\": cow_assignments.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["cow_assignments"]} +{"id": "aplai_course__1_five_floors", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/cpmpy/five_floors.py"], "description": "Baker, Cooper, Fletcher, Miller, and Smith live on the first five floors of an apartment house. Baker does not live on the fifth floor. Cooper does not live on the first floor. Fletcher does not live on either the fifth or the first floor. Miller lives on a higher floor than does Cooper. Smith does not live on a floor adjacent to Fletcher’. Fletcher does not live on a floor adjacent to Cooper’s. They all live on different floors. Find the floors where these people live. Print the floors where each person lives (B, C, F, M, S).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision Variables\nB = intvar(1, 5) # Baker\nC = intvar(1, 5) # Cooper\nF = intvar(1, 5) # Fletcher\nM = intvar(1, 5) # Miller\nS = intvar(1, 5) # Smith\n\n# Constraints\nmodel = Model()\n\nmodel += B != 5 # Baker does not live on the fifth floor\nmodel += C != 1 # Cooper does not live on the first floor\nmodel += (F != 5) & (F != 1) # Fletcher does not live on either the fifth or the first floor\nmodel += M > C # Miller lives on a higher floor than does Cooper\nmodel += abs(S - F) != 1 # Smith does not live on a floor adjacent to Fletcher\nmodel += abs(F - C) != 1 # Fletcher does not live on a floor adjacent to Cooper\nmodel += AllDifferent([B, C, F, M, S]) # They all live on different floors\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"B\": B.value(), \"C\": C.value(), \"F\": F.value(), \"M\": M.value(), \"S\": S.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["M", "C", "F", "B", "S"]} +{"id": "aplai_course__5_grocery", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/grocery2.mzn"], "description": "A kid goes into a grocery store and buys four items. The cashier charges $7.11, the kid pays and is about to leave when the cashier calls the kid back, and says \"Hold on, I multiplied the four items instead of adding them; I’ll try again; Hah, with adding them the price still comes to $7.11\". What were the prices of the four items? Print the prices of the four items (prices) in cents.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\nimport numpy as np\n\n# Parameters\ntotal_price = 711 # total price in cents\nnum_items = 4\n\n# Decision variables (prices are considered in cents)\nprices = intvar(1, total_price, shape=num_items)\n\n# Constraints\nmodel = Model()\n\n# The sum of the prices in cents is equal to the total price in cents\nmodel += sum(prices) == total_price\n\n# The product of the prices should equal to the scaled total price in cents (to account for the multiplication)\nmodel += np.prod(prices) == total_price * (100 ** (num_items - 1))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"prices\": prices.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["prices"]} +{"id": "aplai_course__1_guards_and_apples", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/guards_and_apples.mzn"], "description": "A boy wants to give an apple to a girl. To get to her, he has to pass through five gates, each with a guard. He bribes each guard with half of his apples, plus one. The boy does not have a knife, therefore he gives the guard an integer number of apples. After he’s given the apple to the girl, he has no apples left. Print a list of 6 numbers (apples), containing the number of apples before each gate, plus the number of apples after the last gate.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nnum_gates = 5\n\n# Decision Variables\napples = intvar(0, 100, shape=num_gates + 1) # the number of apples before each gate plus after the last gate\n\n# Constraints\nmodel = Model()\n\n# The boy is left with no apples after giving the apple to the girl, so he has 1 apple after the last gate.\nmodel += apples[-1] == 1\n\n# At each guard, the boy gives half of his apples, plus one.\nfor i in range(1, num_gates + 1):\n has_before = apples[i - 1]\n has_after = apples[i]\n model += has_before == 2 * (has_after + 1)\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"apples\": apples.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["apples"]} +{"id": "aplai_course__5_hardy_1729_square", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/hardy_1729.mzn"], "description": "Find a combination of 4 different numbers between 1 and 100, such that the sum of the squares of the two first numbers is equal to the sum of the squares of the other two numbers, i.e. a^2 + b^2 = c^2 + d^2 for some a, b, c, d in {1, 100}, a != b != c != d. Print the numbers (a, b, c, d).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\nimport numpy as np\n\nrange_min = 1\nrange_max = 100\n\n# Decision variables\na, b, c, d = intvar(range_min, range_max, shape=4)\n\n# Constraints\nmodel = Model()\n\n# Sum of squares of any two numbers is equal to the sum of squares of the other two numbers\nmodel += (a**2 + b**2) == (c**2 + d**2)\n\n# Constraints to ensure all variables are distinct\nmodel += AllDifferent([a, b, c, d])\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"a\": a.value(), \"b\": b.value(), \"c\": c.value(), \"d\": d.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["b", "d", "c", "a"]} +{"id": "aplai_course__3_kidney_exchange", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/kidney_exchange.mzn"], "description": "At the hospital n people are on a waiting list for a kidney’s transplant. We have the information about the compatibility between these people as a directed graph: compatible[i] is the set of people to which i can donate. Given this information, we want to maximize the number of people that receive a new kidney: anyone who gives a kidney must receive one, and no person receives more than one kidney. Print the transplants (transplants) as a list of lists, where transplants[i][j] is 1 if person i donates to person j, and 0 otherwise.", "input_data": "num_people = 8 # number of people compatible = [ # 1-based indexing, compatible[i] is the list of people to which i can donate [2, 3], [1, 6], [1, 4, 7], [2], [2], [5], [8], [3] ]", "model": "# Data\nnum_people = 8 # number of people\ncompatible = [ # 1-based indexing, compatible[i] is the list of people to which i can donate\n [2, 3],\n [1, 6],\n [1, 4, 7],\n [2],\n [2],\n [5],\n [8],\n [3]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\ntransplants = boolvar(shape=(num_people, num_people)) # transplants[i][j] is True if i donates to j\n\n# Model setup\nmodel = Model()\n\n# Constraints for the transplant pairs\nfor i in range(num_people):\n # Anyone who gives a kidney must receive one\n gives_kidney = sum(transplants[i, :]) >= 1\n receives_kidney = sum(transplants[:, i]) >= 1\n model += gives_kidney.implies(receives_kidney)\n\n # Each person can donate to at most one person and receive from at most one person\n can_donate_once = sum(transplants[i, :]) <= 1\n can_receive_once = sum(transplants[:, i]) <= 1\n model += can_donate_once & can_receive_once\n\n # Compatibility constraint: if i can't donate to j, then transplants[i][j] must be 0 (adjust for 0-based indexing)\n model += [transplants[i, j] == 0 for j in range(num_people) if j + 1 not in compatible[i]]\n\n# Objective: maximize the number of transplants\nmodel.maximize(sum(transplants))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"transplants\": transplants.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["transplants"]} +{"id": "aplai_course__1_magic_square", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/magic_square.mzn"], "description": "A magic square is an n x n grid (n != 2) such that each cell contains a different integer from 1 to n^2 and the sum of the integers in each row, column and diagonal is equal. Find a magic square for size 4, knowing that the sum of integers of each row, column and diagonal has to be equal to n(n^2+ 1)/2 (integer). Print the magic square as a list of lists (square).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nn = 4 # size of the magic square\nmagic_sum = n * (n**2 + 1) // 2 # sum of each row, column and diagonal\n\n# Decision Variables\nsquare = intvar(1, n ** 2, shape=(n, n)) # the magic square\n\n# Constraints\nmodel = Model()\n\n# All numbers in the magic square must be different\nmodel += AllDifferent(square)\n\n# The sum of the numbers in each row must be equal to the magic sum\nfor i in range(n):\n model += sum(square[i, :]) == magic_sum\n\n# The sum of the numbers in each column must be equal to the magic sum\nfor j in range(n):\n model += sum(square[:, j]) == magic_sum\n\n# The sum of the numbers in the main diagonal must be equal to the magic sum\nmodel += sum(square[i, i] for i in range(n)) == magic_sum\n\n# The sum of the numbers in the other diagonal must be equal to the magic sum\nmodel += sum(square[i, n - 1 - i] for i in range(n)) == magic_sum\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"square\": square.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["square"]} +{"id": "aplai_course__2_maximal_independent_sets", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/maximal_independent_sets.mzn"], "description": "In graph theory, an independent set is a set of vertices in a graph, no two of which are adjacent. A maximal independent set is an independent set that is not a subset of any other independent set. A graph may have many maximal independent sets of widely varying sizes: find a maximal independent set for the data provided. The data provides an array containing for each node of the graph the set of adjacent nodes. Print whether each node is included in the maximal independent set (nodes).", "input_data": "n = 8 # number of nodes in the graph adjacency_list = [ # adjacency list for each node in the graph [2, 3, 7], [1, 4, 8], [1, 4, 5], [2, 3, 6], [3, 6, 7], [4, 5, 8], [1, 5, 8], [2, 6, 7] ]", "model": "# Data\nn = 8 # number of nodes in the graph\nadjacency_list = [ # adjacency list for each node in the graph\n [2, 3, 7],\n [1, 4, 8],\n [1, 4, 5],\n [2, 3, 6],\n [3, 6, 7],\n [4, 5, 8],\n [1, 5, 8],\n [2, 6, 7]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n\n# Create a binary decision variable for each node to indicate if it's included in the independent set\nnodes = boolvar(shape=n)\n\n# Model setup\nmodel = Model()\n\n# Constraint: No two adjacent nodes can both be in the independent set\nfor i, neighbors in enumerate(adjacency_list):\n for neighbor in neighbors:\n # Subtract 1 to adjust for 1-based indexing in the data\n neighbor_idx = neighbor - 1\n # Ensure that for every edge, at least one of its endpoints is not in the independent set\n model += ~(nodes[i] & nodes[neighbor_idx])\n\n# Objective: Maximize the number of nodes in the independent set\nmodel.maximize(sum(nodes))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"nodes\": nodes.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["nodes"]} +{"id": "aplai_course__1_money_change", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/money_change.mzn"], "description": "Alice has to give Bob change of 199 euros. She has 6 different types of coins of different value ([1, 2, 5, 10, 25, 50]) and she has a certain number of coins of each value available ([20, 10, 15, 8, 4, 2]). How can the change be composed with the available coins minimizing the number of coins used? Print the number of coins of each type to give to Bob (coin_counts).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\namount = 199 # amount of money to give to Bob\nn = 6 # number of types of coins\ntypes_of_coins = [1, 2, 5, 10, 25, 50] # value of each type of coin\navailable_coins = [20, 10, 15, 8, 4, 2] # number of available coins of each type\n\n# Decision Variables\ncoin_counts = intvar(0, 20, shape=n) # number of coins of each type to give to Bob\n\n# Constraints\nmodel = Model()\n\n# The sum of the coins given to Bob must be equal to the amount of money to give him\nmodel += sum(coin_counts[i] * types_of_coins[i] for i in range(n)) == amount\n\n# The number of each type of coin given to Bob must not exceed the available coins\nfor i in range(n):\n model += coin_counts[i] <= available_coins[i]\n\n# Objective: Minimize the total number of coins given to Bob\nmodel.minimize(sum(coin_counts))\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"coin_counts\": coin_counts.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["coin_counts"]} +{"id": "aplai_course__2_movie_scheduling", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/movie_scheduling.mzn", "# Source description: Steven S. Skiena's The Algorithm Design Manual"], "description": "Consider the following scheduling problem. Imagine you are a highly-in- demand actor, who has been presented with offers to star in n different movie projects under development. Each offer comes specified with the first and last day of filming. To take the job, you must commit to being available throughout this entire period. Thus, you cannot simultaneously accept two jobs whose intervals overlap. For an artist such as yourself, the criteria for job acceptance is clear: you want to make as much money as possible. Because each of these films pays the same fee per film, this implies you seek the largest possible set of jobs (intervals) such that no two of them conflict with each other. Input is a list of movies along with their first and last day of filming Print the number of movies accepted (num_selected_movies) as well as which movies are accepted (selected_movies) as a list of 0s and 1s, where 1 indicates that the movie is selected and 0 indicates that it is not selected (in the order of the input list).", "input_data": "movies = [ # title, start, end [\"Tarjan of the Jungle\", 4, 13], [\"The Four Volume Problem\", 17, 27], [\"The President's Algorist\", 1, 10], [\"Steiner's Tree\", 12, 18], [\"Process Terminated\", 23, 30], [\"Halting State\", 9, 16], [\"Programming Challenges\", 19, 25], [\"Discrete Mathematics\", 2, 7], [\"Calculated Bets\", 26, 31] ]", "model": "# Data\nmovies = [ # title, start, end\n [\"Tarjan of the Jungle\", 4, 13],\n [\"The Four Volume Problem\", 17, 27],\n [\"The President's Algorist\", 1, 10],\n [\"Steiner's Tree\", 12, 18],\n [\"Process Terminated\", 23, 30],\n [\"Halting State\", 9, 16],\n [\"Programming Challenges\", 19, 25],\n [\"Discrete Mathematics\", 2, 7],\n [\"Calculated Bets\", 26, 31]\n]\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nnum_movies = len(movies)\n\n# Decision Variables\nselected_movies = boolvar(shape=num_movies, name=\"selected_movies\") # 1 if the movie is selected, 0 otherwise\nnum_selected_movies = sum(selected_movies) # Number of selected movies\n\n# Model\nmodel = Model()\n\n# Add constraint for non-overlapping movie schedules\nfor i in range(num_movies):\n for j in range(num_movies):\n # Check if the intervals overlap for each pair of movies\n if (i != j # Different movies\n and movies[i][2] > movies[j][1] # Movie i ends after movie j starts\n and movies[j][2] > movies[i][1] # Movie j ends after movie i starts\n ):\n # Then, the movies cannot be selected together\n model += selected_movies[i] + selected_movies[j] <= 1\n\n# Objective: Maximize the number of selected movies\nmodel.maximize(num_selected_movies)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"num_selected_movies\": model.objective_value(),\n \"selected_movies\": selected_movies.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["in the order of the input list", "selected_movies", "num_selected_movies"]} +{"id": "aplai_course__3_people_in_a_room", "category": "aplai_course", "metadata": ["#!/usr/bin/python3"], "description": "There are 13 people. 4 of them are male. They randomly enter a room one at a time. Find a way that the males and females enter so that the ratio of females to males in the room at any one time is no greater than 7/3? Print the sequence of people entering the room (sequence), where 0 represents male and 1 represents female.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\ntotal_people = 13\nnum_males = 4\n\n# Decision variable: 0 for male, 1 for female\nsequence = boolvar(shape=total_people)\n\n# Constraints\nmodel = Model()\n\n# Ensure exactly number of males and females\nmodel += [sum(sequence) == total_people - num_males]\n\n# Add constraints for the ratio at each point in the sequence\nfor i in range(1, total_people):\n total_females_so_far = sum(sequence[:i])\n total_males_so_far = i - sum(sequence[:i])\n # Number of females to males is no greater than 7/3, or 3 times the females is less than or equal to 7 times the males\n model += (3 * total_females_so_far) <= (7 * total_males_so_far)\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"sequence\": sequence.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["sequence"]} +{"id": "aplai_course__2_subsets_100", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/subsets_100.mzn"], "description": "Out of the set of integers 1,...,100 you are given ten different integers ([81 21 79 4 29 70 28 20 14 7]). From this set A of ten integers you can always find two disjoint non-empty subsets, S and T, such that the sum of elements in S equals the sum of elements in T. Note: S union T does not need to be all ten elements of A. Find sets S and T for the given set A. Print which elements are in S (in_S) and which elements are in T (in_T), with 2 lists of length 10, where 1 means that the element is in the subset and 0 means that it is not.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nA = [81, 21, 79, 4, 29, 70, 28, 20, 14, 7]\n\n# Decision variables: 1 if an element is in the subset, 0 otherwise\nin_S = boolvar(shape=len(A))\nin_T = boolvar(shape=len(A))\n\n# Model setup\nmodel = Model()\n\n# Constraint: sum of elements in S equals sum of elements in T\nmodel += (sum(in_S * A) == sum(in_T * A))\n\n# S and T are disjoint, so there is no element that is in both S and T\nmodel += (sum(in_S * in_T) == 0)\n\n# S and T are non-empty\nmodel += (sum(in_S) > 0)\nmodel += (sum(in_T) > 0)\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"in_S\": in_S.value().tolist(), \"in_T\": in_T.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["in_S", "in_T"]} +{"id": "aplai_course__2_subset_sum", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/subset_sum.mzn"], "description": "A bank van had several bags of coins, each containing either 16, 17, 23, 24, 39, or 40 coins (there are multiple bags of the same kind). While the van was parked on the street, thieves stole some bags. A total of 100 coins were lost. It is required to find how many bags were stolen for each type of coin bag. Print the number of bags stolen for each type of coins (bags).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\ntotal_coins_lost = 100\ncoin_numbers = [16, 17, 23, 24, 39, 40]\n\n# Decision variables\n# The number of bags stolen for each type of coins\nbags = intvar(0, total_coins_lost, shape=len(coin_numbers))\n\n# Constraints\nmodel = Model()\n\n# The total number of coins lost is equal to the sum of the coins in the stolen bags\nmodel += sum([bags[i] * coin_numbers[i] for i in range(len(coin_numbers))]) == total_coins_lost\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\"bags\": bags.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["bags"]} +{"id": "aplai_course__1_thick_as_thieves", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/thick_as_thieves.mzn"], "description": "Following a robbery at Sparkles the Jeweller’s, Inspector Korner of the Yard interviewed six of the usual suspects. He knew that the getaway car had been barely big enough to hold two, so he reckoned that at least four of them were innocent - but which ones? He also supposed that the innocent ones would tell the truth, while the guilty one or ones would lie. What they actually said was: - ARTIE: \"It wasn't me.\" - BILL: \"Crackitt was in it up to his neck.\" - CRACKITT: \"No I wasn't.\" - DODGY: \"If Crackitt did it, Bill did it with him.\" - EDGY: \"Nobody did it alone.\" - FINGERS: \"That’s right: it was Artie and Dodgy together.\" If the good inspector’s suppositions were correct, who is guilty? Print whether each suspect is guilty or not (artie, bill, crackitt, dodgy, edgy, fingers).", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision Variables for each suspect representing if they are guilty\nartie = boolvar(name=\"Artie\")\nbill = boolvar(name=\"Bill\")\ncrackitt = boolvar(name=\"Crackitt\")\ndodgy = boolvar(name=\"Dodgy\")\nedgy = boolvar(name=\"Edgy\")\nfingers = boolvar(name=\"Fingers\")\nsuspects = [artie, bill, crackitt, dodgy, edgy, fingers]\n\n# Constraints\nmodel = Model()\n\n# At most two are guilty because the getaway car was small\nmodel += sum(suspects) <= 2\n\n# Statement Constraints; if the suspect is guilty, they are lying, so their statement is false\n\n# Artie: \"It wasn't me.\"\nartie_statement = ~artie\nmodel += artie == ~artie_statement\n\n# Bill: \"Crackitt was in it up to his neck.\"\nbill_statement = crackitt\nmodel += bill == ~bill_statement\n\n# Crackitt: \"No I wasn't.\"\ncrackitt_statement = ~crackitt\nmodel += crackitt == ~crackitt_statement\n\n# Dodgy: \"If Crackitt did it, Bill did it with him.\"\ndodgy_statement = crackitt.implies(bill)\nmodel += dodgy == ~dodgy_statement\n\n# Edgy: \"Nobody did it alone.\"\nedgy_statement = sum(suspects) > 1\nmodel += edgy == ~edgy_statement\n\n# Fingers: \"That’s right: it was Artie and Dodgy together.\"\nfingers_statement = artie & dodgy\nmodel += fingers == ~fingers_statement\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"artie\": int(artie.value()),\n \"bill\": int(bill.value()),\n \"crackitt\": int(crackitt.value()),\n \"dodgy\": int(dodgy.value()),\n \"edgy\": int(edgy.value()),\n \"fingers\": int(fingers.value())\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["dodgy", "fingers", "edgy", "bill", "artie", "crackitt"]}