diff --git "a/dataset.jsonl" "b/dataset.jsonl" --- "a/dataset.jsonl" +++ "b/dataset.jsonl" @@ -1,28 +1,28 @@ -{"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": "001: Car Sequencing 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_002_template_design", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob002_template_design.py", "# Source description: https://www.csplib.org/Problems/prob002/"], "description": "002: Template Design This problem arises from a colour printing firm which produces a variety of products from thin board, including cartons for human and animal food and magazine inserts. Food products, for example, are often marketed as a basic brand with several variations (typically flavours). Packaging for such variations usually has the same overall design, in particular the same size and shape, but differs in a small proportion of the text displayed and/or in colour. For instance, two variations of a cat food carton may differ only in that on one is printed ‘Chicken Flavour’ on a blue background whereas the other has ‘Rabbit Flavour’ printed on a green background. A typical order is for a variety of quantities of several design variations. Because each variation is identical in dimension, we know in advance exactly how many items can be printed on each mother sheet of board, whose dimensions are largely determined by the dimensions of the printing machinery. Each mother sheet is printed from a template, consisting of a thin aluminium sheet on which the design for several of the variations is etched. The problem is to decide, firstly, how many distinct templates to produce, and secondly, which variations, and how many copies of each, to include on each template. The given example is based on data from an order for cartons for different varieties of dry cat-food. Print the number of printed sheets (production) and the layout of the templates (layout).", "input_data": "n_slots = 9 # The amount of slots on a template n_templates = 2 # The amount of templates n_var = 7 # The amount of different variations demand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation", "model": "# Data\nn_slots = 9 # The amount of slots on a template\nn_templates = 2 # The amount of templates\nn_var = 7 # The amount of different variations\ndemand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nub = max(demand) # The upper bound for the production\n\n# create model\nmodel = Model()\n\n# decision variables\nproduction = intvar(1, ub, shape=n_templates, name=\"production\")\nlayout = intvar(0, n_var, shape=(n_templates, n_var), name=\"layout\")\n\n# all slots are populated in a template\nmodel += all(sum(layout[i]) == n_slots for i in range(n_templates))\n\n# meet demand\nfor var in range(n_var):\n model += sum(production * layout[:, var]) >= demand[var]\n\n# break symmetry\n# equal demand\nfor i in range(n_var - 1):\n if demand[i] == demand[i + 1]:\n model += layout[0, i] <= layout[0, i + 1]\n for j in range(n_templates - 1):\n model += (layout[j, i] == layout[j, i + 1]).implies(layout[j + 1, i] <= layout[j + 1, i + 1])\n\n# distinguish templates\nfor i in range(n_templates - 1):\n model += production[i] <= production[i + 1]\n\n# static symmetry\nfor i in range(n_var - 1):\n if demand[i] < demand[i + 1]:\n model += sum(production * layout[:, i]) <= sum(production * layout[:, i + 1])\n\n# minimize number of printed sheets\nmodel.minimize(sum(production))\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"production\": production.value().tolist(), \"layout\": layout.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["production", "layout"]} -{"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": "005: Low Autocorrelation Binary Sequences: 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_006_golomb_rules", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob006_golomb.py", "# Source description: https://www.csplib.org/Problems/prob006/"], "description": "006: Golomb rulers These problems are said to have many practical applications including sensor placements for x-ray crystallography and radio astronomy. A Golomb ruler may be defined as a set of \\( m \\) integers \\( 0 = a_1 < a_2 < \\cdots < a_m \\) such that the \\( \\frac{m(m-1)}{2} \\) differences \\( a_j - a_i, \\, 1 \\leq i < j \\leq m \\) are distinct. Such a ruler is said to contain \\( m \\) marks and is of length \\( a_m \\). The objective is to find optimal (minimum length) or near-optimal rulers. Note that a symmetry can be removed by adding the constraint that \\( a_2 - a_1 < a_m - a_{m-1} \\), the first difference is less than the last. There is no requirement that a Golomb ruler measures all distances up to its length - the only requirement is that each distance is only measured in one way. However, if a ruler does measure all distances, it is classified as a perfect Golomb ruler. There exist several interesting generalizations of the problem which have received attention like modular Golomb rulers (differences are all distinct mod a given base), disjoint Golomb rulers, Golomb rectangles (the 2-dimensional generalization of Golomb rulers), and difference triangle sets (sets of rulers with no common difference). Print the positions of the marks (marks) and the total length of the Golomb ruler (length).", "input_data": "size = 10 # Number of marks on the Golomb ruler", "model": "# Data\nsize = 10 # Number of marks on the Golomb ruler\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\nmarks = intvar(0, size * size, shape=size, name=\"marks\")\nlength = marks[-1]\n\n# Model\nmodel = Model()\n\n# first mark is 0\nmodel += (marks[0] == 0)\n\n# marks must be increasing\nmodel += marks[:-1] < marks[1:]\n\n# golomb constraint\ndiffs = [marks[j] - marks[i] for i in range(0, size - 1) for j in range(i + 1, size)]\nmodel += AllDifferent(diffs)\n\n# Symmetry breaking\nmodel += (marks[size - 1] - marks[size - 2] > marks[1] - marks[0])\nmodel += (diffs[0] < diffs[size - 1])\n\n# find optimal ruler\nmodel.minimize(length)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"marks\": marks.value().tolist(), \"length\": length.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["marks", "length"]} -{"id": "csplib__csplib_007_all_interval", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob007_all_interval.py", "# Source description: https://www.csplib.org/Problems/prob007/"], "description": "007: All-Interval Series Given the twelve standard pitch-classes (c, c#, d, …), represented by numbers \\(0, 1, \\ldots, 11\\), find a series in which each pitch-class occurs exactly once and in which the musical intervals between neighbouring notes cover the full set of intervals from the minor second (1 semitone) to the major seventh (11 semitones). That is, for each of the intervals, there is a pair of neighbouring pitch-classes in the series, between which this interval appears. The problem of finding such a series can be easily formulated as an instance of a more general arithmetic problem on \\(\\mathbb{Z}_n\\), the set of integer residues modulo \\(n\\). Given \\(n \\in \\mathbb{N}\\), find a vector \\(s = (s_1, \\ldots, s_n)\\), such that - \\(s\\) is a permutation of \\(\\mathbb{Z}_n = \\{0, 1, \\ldots, n-1\\}\\); and - the interval vector \\(v = (|s_2 - s_1|, |s_3 - s_2|, \\ldots, |s_n - s_{n-1}|)\\) is a permutation of \\(\\mathbb{Z}_n \\setminus \\{0\\} = \\{1, 2, \\ldots, n-1\\}\\). A vector \\(v\\) satisfying these conditions is called an all-interval series of size \\(n\\); the problem of finding such a series is the all-interval series problem of size \\(n\\). We may also be interested in finding all possible series of a given size. The All-Interval Series is a special case of the Graceful Graphs in which the graph is a line. Print the sequence of pitch-classes (x) and the corresponding intervals (diffs).", "input_data": "n = 12 # Number of pitch-classes", "model": "# Data\nn = 12 # Number of pitch-classes\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Create the solver\nmodel = Model()\n\n# Declare variables\nx = intvar(0, n - 1, shape=n, name=\"x\") # Pitch-classes\ndiffs = intvar(1, n - 1, shape=n - 1, name=\"diffs\") # Intervals\n\n# Constraints\nmodel += [AllDifferent(x),\n AllDifferent(diffs)]\n\n# Differences between successive values\nmodel += diffs == np.abs(x[1:] - x[:-1])\n\n# Symmetry breaking\nmodel += [x[0] < x[-1]] # Mirroring array is equivalent solution\nmodel += [diffs[0] < diffs[1]] # Further symmetry breaking\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"x\": x.value().tolist(), \"diffs\": diffs.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["diffs", "x"]} -{"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": "008: Vessel Loading 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": "009: Perfect Square Placement 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_010_social_golfers_problem", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob010_social_golfers.py", "# Source description: https://www.csplib.org/Problems/prob010/"], "description": "010: Social Golfers Problem The coordinator of a local golf club has come to you with the following problem. In their club, there are 32 social golfers, each of whom play golf once a week, and always in groups of 4. They would like you to come up with a schedule of play for these golfers, to last as many weeks as possible, such that no golfer plays in the same group as any other golfer on more than one occasion. Possible variants of the above problem include: finding a 10-week schedule with \"maximum socialisation\"; that is, as few repeated pairs as possible (this has the same solutions as the original problem if it is possible to have no repeated pairs), and finding a schedule of minimum length such that each golfer plays with every other golfer at least once (\"full socialisation\"). The problem can easily be generalized to that of scheduling \\( m \\) groups of \\( n \\) golfers over \\( p \\) weeks, such that no golfer plays in the same group as any other golfer twice (i.e. maximum socialisation is achieved). This problem is derived from a question posted to sci.op-research by bigwind777@aol.com (Bigwind777) in May 1998. It is a generalisation of the problem of constructing a round-robin tournament schedule, where the number of players in a \"game\" is more than two. The optimal solution for 32 golfers is not yet known. Print the assignments of golfers to groups for each week (assign).", "input_data": "n_weeks = 4 # Number of weeks n_groups = 3 # Number of groups group_size = 3 # Size of each group", "model": "# Data\nn_weeks = 4 # Number of weeks\nn_groups = 3 # Number of groups\ngroup_size = 3 # Size of each group\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\nimport numpy as np\nimport json\n\n\ndef social_golfers(n_weeks, n_groups, group_size):\n\n n_golfers = n_groups * group_size\n golfers = np.arange(n_golfers)\n weeks = np.arange(n_weeks)\n groups = np.arange(n_groups)\n\n # Possible configurations\n assign = intvar(0, n_groups - 1, shape=(n_golfers, n_weeks), name=\"assign\")\n\n model = Model()\n\n # C1: Each group has exactly group_size players\n for gr in groups:\n for w in weeks:\n model += sum(assign[:, w] == gr) == group_size\n\n # C2: Each pair of players only meets at most once\n for g1, g2 in all_pairs(golfers):\n model += sum(assign[g1] == assign[g2]) <= 1\n\n # SBSA: Symmetry-breaking by selective assignment\n # On the first week, the first group_size golfers play in group 1, the\n # second group_size golfers play in group 2, etc. On the second week,\n # golfer 1 plays in group 1, golfer 2 plays in group 2, etc.\n # model += [assign[:, 0] == (golfers // group_size)]\n\n for g in golfers:\n if g < group_size:\n model += [assign[g, 1] == g]\n\n # First golfer always in group 0\n model += [assign[0, :] == 0]\n\n return model, assign\n\n# Example usage\nmodel, assign = social_golfers(n_weeks, n_groups, group_size)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"assign\": assign.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["assign"]} -{"id": "csplib__csplib_011_acc_basketball_schedule", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob011_basketball_schedule.py", "# Source description: https://www.csplib.org/Problems/prob011/"], "description": "011: ACC Basketball Schedule The problem is finding a timetable for the 1997/98 Atlantic Coast Conference (ACC) in basketball. It was first tackled by Nemhauser and Trick. The 9 basketball teams in the tournament are Clemson (Clem), Duke (Duke), Florida State (FSU), Georgia Tech (GT), Maryland (UMD), North Carolina (UNC), North Carolina State (NCSt), Virginia (UVA), and Wake Forest (Wake). The problem is to determine a double round robin schedule for these 9 teams subject to some additional constraints. In a double round robin, each team plays each other, once at home, once away. The schedule is to be played over 18 dates. The first and all subsequent odd dates are weekday fixtures. The second and all subsequent even dates are weekend fixtures. There are nine other sets of constraints. 1. Mirroring. The dates are grouped into pairs (r1, r2), such that each team will get to play against the same team in dates r1 and r2. Such a grouping is called a mirroring scheme. Nemhauser and Trick use the mirroring scheme {(1, 8), (2, 9), (3, 12), (4, 13), (5, 14), (6, 15), (7, 16), (10, 17), (11, 18)} 2. No Two Final Aways. No team can play away on both last dates. 3. Home/Away/Bye Pattern Constraints. No team may have more than two away matches in a row. No team may have more than two home matches in a row. No team may have more than three away matches or byes in a row. No team may have more than four home matches or byes in a row. 4. Weekend Pattern. Of the weekends, each team plays four at home, four away, and one bye. 5. First Weekends. Each team must have home matches or byes at least on two of the first five weekends. 6. Rival Matches. Every team except FSU has a traditional rival. The rival pairs are Duke-UNC, Clem-GT, NCSt-Wake, and UMD-UVA. In the last date, every team except FSU plays against its rival, unless it plays against FSU or has a bye. 7. Constrained Matches. The following pairings must occur at least once in dates 11 to 18: Wake-UNC, Wake-Duke, GT-UNC, and GT-Duke. 8. Opponent Sequence Constraints. No team plays in two consecutive dates away against UNC and Duke. No team plays in three consecutive dates against UNC, Duke and Wake (independent of home/away). 9. Other Constraints. UNC plays its rival Duke in the last date and in date 11. UNC plays Clem in the second date. Duke has a bye in date 16. Wake does not play home in date 17. Wake has a bye in the first date. Clem, Duke, UMD and Wake do not play away in the last date. Clem, FSU, GT and Wake do not play away in the first date. Neither FSU nor NCSt have a bye in the last date. UNC does not have a bye in the first date. Print the match configuration (config) and whether the team is playing home, away, or has a bye (where).", "input_data": "n_teams = 9 n_days = 18", "model": "# Data\nn_teams = 9\nn_days = 18\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n\ndef basketball_schedule():\n n_teams = 9\n n_days = 18\n\n # Teams\n teams = np.arange(n_teams)\n CLEM, DUKE, FSU, GT, UMD, UNC, NCSt, UVA, WAKE = teams\n rivals = [GT, UNC, FSU, CLEM, UVA, DUKE, WAKE, UMD, NCSt]\n\n # Days\n days = np.arange(n_days)\n weekdays = np.where(days % 2 == 0)[0]\n weekends = np.where(days % 2 == 1)[0]\n\n # matrix indicating which teams play against each other at what date\n # config[d,i] == j iff team i plays team j on day d of the tournament\n # config[d,i] == i iff team i plays bye on day d of the tournament\n config = intvar(0, n_teams - 1, shape=(n_days, n_teams), name=\"config\")\n # home[d,i] == True iff team i plays home on day d of the tournament\n where = intvar(0, 2, shape=(n_days, n_teams), name=\"where\")\n HOME, BYE, AWAY = 0, 1, 2\n\n model = Model()\n\n # a team cannot have different opponents on the same day\n for day_conf in config:\n model += AllDifferent(day_conf)\n\n # team plays itself when playing BYE\n for day in range(n_days):\n model += (config[day] == teams) == (where[day] == BYE)\n\n # symmetry\n for day in range(n_days):\n for t in range(n_teams):\n model += config[day, config[day, t]] == t\n\n # 1. mirroring constraint\n scheme = np.array([7, 8, 11, 12, 13, 14, 15, 0, 1, 16, 17, 2, 3, 4, 5, 6, 9, 10])\n model += config == config[scheme]\n model += where == (2 - where[scheme])\n\n # 2. no two final days away\n for t in range(n_teams):\n model += sum(where[-2:, t] == AWAY) <= 1\n\n # 3. home/away/bye pattern constraint\n for t in teams:\n for d in days[:-3]:\n # No team may have more than two home matches in a row\n model += sum(where[d:d + 3, t] == HOME) <= 2\n # No team may have more than two away matches in a row\n model += sum(where[d:d + 3, t] == AWAY) <= 2\n\n for d in days[:-4]:\n # No team may have more than three away matches or byes in a row\n model += sum((where[d:d + 4, t] == AWAY) |\n (where[d:d + 4, t] == BYE)) <= 3\n\n for d in days[:-5]:\n # No team may have more than four home matches or byes in a row.\n model += sum((where[d:d + 5, t] == HOME) |\n (where[d:d + 5, t] == BYE)) <= 4\n\n # 4. weekend pattern constraint\n # Of the weekends, each team plays four at home, four away, and one bye.\n for t in range(n_teams):\n model += sum(where[weekends, t] == HOME) == 4\n model += sum(where[weekends, t] == AWAY) == 4\n model += sum(where[weekends, t] == BYE) == 1\n\n # 5. first weekends constraint\n # Each team must have home matches or byes at least on two of the first five weekends.\n for t in range(n_teams):\n model += (sum(where[weekends[:5], t] == HOME) +\n sum(where[weekends[:5], t] == BYE)) >= 2\n\n # 6. rival matches constraint\n # In the last date, every team except FSU plays against its rival, unless it plays against FSU or has a bye.\n for t in teams:\n if t != FSU:\n model += (config[-1, t] == rivals[t]) | \\\n (config[-1, t] == FSU) | \\\n (where[-1, t] == BYE)\n\n # 7. Constrained matches\n # The following pairings must occur at least once in dates 11 to 18:\n # Wake-UNC, Wake-Duke, GT-UNC, and GT-Duke.\n model += sum(config[10:, WAKE] == UNC) >= 1\n model += sum(config[10:, WAKE] == DUKE) >= 1\n model += sum(config[10:, GT] == UNC) >= 1\n model += sum(config[10:, GT] == DUKE) >= 1\n\n # 8. Opponent Sequence constraints\n for t in teams:\n for d in days[:-2]:\n if t != DUKE and t != UNC:\n # No team plays in two consecutive dates away against UNC and Duke\n model += ((config[d, t] == UNC) & (where[d, t] == AWAY) &\n (config[d + 1, t] == DUKE) & (where[d + 1, t] == AWAY)).implies(False)\n model += ((config[d, t] == DUKE) & (where[d, t] == AWAY) &\n (config[d + 1, t] == UNC) & (where[d + 1, t] == AWAY)).implies(False)\n for d in days[:-3]:\n if t not in [UNC, DUKE, WAKE]:\n # No team plays in three consecutive dates against UNC, Duke and Wake (independent of home/away).\n model += ((config[d, t] == UNC) & (config[d + 1, t] == DUKE) & (config[d + 2, t] == WAKE)).implies(\n False)\n model += ((config[d, t] == UNC) & (config[d + 1, t] == WAKE) & (config[d + 2, t] == DUKE)).implies(\n False)\n model += ((config[d, t] == DUKE) & (config[d + 1, t] == UNC) & (config[d + 2, t] == WAKE)).implies(\n False)\n model += ((config[d, t] == DUKE) & (config[d + 1, t] == WAKE) & (config[d + 2, t] == UNC)).implies(\n False)\n model += ((config[d, t] == WAKE) & (config[d + 1, t] == UNC) & (config[d + 2, t] == DUKE)).implies(\n False)\n model += ((config[d, t] == WAKE) & (config[d + 1, t] == DUKE) & (config[d + 2, t] == UNC)).implies(\n False)\n\n # 9. Other constraints\n # UNC plays its rival Duke in the last date and in date 11\n model += config[10, UNC] == DUKE\n model += config[-1, UNC] == DUKE\n # UNC plays Clem in the second date\n model += config[1, UNC] == CLEM\n # Duke has a bye in date 16\n model += where[15, DUKE] == BYE\n # Wake does not play home in date 17\n model += where[16, WAKE] != HOME\n # Wake has a bye in the first date\n model += where[0, WAKE] == BYE\n # Clem, Duke, UMD and Wake do not play away in the last date\n model += where[-1, [CLEM, DUKE, UMD, WAKE]] != AWAY\n # Clem, FSU, GT and Wake do not play away in the first date\n model += where[0, [CLEM, FSU, GT, WAKE]] != AWAY\n # Neither FSU nor NCSt have a bye in last date\n model += where[-1, [FSU, NCSt]] != BYE\n # UNC does not have a bye in the first date.\n model += where[0, UNC] != BYE\n\n return model, (config, where)\n\n\n# Example usage\nmodel, (config, where) = basketball_schedule()\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"config\": config.value().tolist(),\n \"where\": where.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["config", "where"]} -{"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": "012: Nonogram 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_013_progressive_party_problem", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob013_progressive_party.py", "# Source description: https://www.csplib.org/Problems/prob013/"], "description": "013: Progressive Party Problem (PPP) The problem is to timetable a party at a yacht club. Certain boats are to be designated hosts, and the crews of the remaining boats in turn visit the host boats for several successive half-hour periods. The crew of a host boat remains on board to act as hosts while the crew of a guest boat together visits several hosts. Every boat can only hold a limited number of people at a time (its capacity) and crew sizes are different. The total number of people aboard a boat, including the host crew and guest crews, must not exceed the capacity. A guest boat cannot not revisit a host and guest crews cannot meet more than once. The problem facing the rally organizer is that of minimizing the number of host boats. Print the visit schedule (visits) and the host designations (is_host).", "input_data": "n_boats = 5 # Number of boats n_periods = 4 # Number of periods capacity = [6, 8, 12, 12, 12] # Capacities of the boats crew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats", "model": "# Data\nn_boats = 5 # Number of boats\nn_periods = 4 # Number of periods\ncapacity = [6, 8, 12, 12, 12] # Capacities of the boats\ncrew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\n\ndef progressive_party(n_boats, n_periods, capacity, crew_size, **kwargs):\n is_host = boolvar(shape=n_boats, name=\"is_host\")\n visits = intvar(0, n_boats - 1, shape=(n_periods, n_boats), name=\"visits\")\n\n model = Model()\n\n # Crews of host boats stay on boat\n for boat in range(n_boats):\n model += (is_host[boat]).implies((visits[:, boat] == boat).all())\n\n # Number of visitors can never exceed capacity of boat\n for slot in range(n_periods):\n for boat in range(n_boats):\n model += sum((visits[slot] == boat) * crew_size) + crew_size[boat] * is_host[boat] <= capacity[boat]\n\n # Guests cannot visit a boat twice\n for boat in range(n_boats):\n model += (~is_host[boat]).implies(AllDifferent(visits[:, boat]))\n\n # Non-host boats cannot be visited\n for boat in range(n_boats):\n model += (~is_host[boat]).implies((visits != boat).all())\n\n # Crews cannot meet more than once\n for c1, c2 in all_pairs(range(n_boats)):\n model += sum(visits[:, c1] == visits[:, c2]) <= 1\n\n # Minimize number of hosts needed\n model.minimize(sum(is_host))\n\n return model, (visits, is_host)\n\n\n# Example usage\nmodel, (visits, is_host) = progressive_party(n_boats, n_periods, capacity, crew_size)\nmodel.solve()\n\n# Print\nsolution = {\n \"visits\": visits.value().tolist(),\n \"is_host\": is_host.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["is_host", "visits"]} -{"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": "015: Schur's Lemma 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_019_magic_squares_and_sequences", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob019_magic_sequence.py", "# Source description: https://www.csplib.org/Problems/prob019/"], "description": "019: Magic Squares and Sequences An order \\( n \\) magic square is a \\( n \\) by \\( n \\) matrix containing the numbers 1 to \\( n^2 \\), with each row, column, and main diagonal equal to the same sum. As well as finding magic squares, we are interested in the number of a given size that exist. There are several interesting variations. For example, we may insist on certain values in certain squares (like in quasigroup completion) and ask if the magic square can be completed. In a heterosquare, each row, column, and diagonal sums to a different value. In an anti-magic square, the row, column, and diagonal sums form a sequence of consecutive integers. A magic sequence of length \\( n \\) is a sequence of integers \\( x_0, \\ldots, x_{n-1} \\) between 0 and \\( n-1 \\), such that for all \\( i \\) in 0 to \\( n-1 \\), the number \\( i \\) occurs exactly \\( x_i \\) times in the sequence. For instance, 6, 2, 1, 0, 0, 0, 1, 0, 0, 0 is a magic sequence since 0 occurs 6 times in it, 1 occurs twice, etc. Print the magic sequence (x).", "input_data": "n = 12 # Length of the magic sequence", "model": "# Data\nn = 12 # Length of the magic sequence\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef magic_sequence(n):\n model = Model()\n\n x = intvar(0, n - 1, shape=n, name=\"x\")\n\n # Constraints\n for i in range(n):\n model += x[i] == sum(x == i)\n\n # Speedup search\n model += sum(x) == n\n model += sum(x * np.arange(n)) == n\n\n return model, (x,)\n\n# Example usage\nmodel, (x,) = magic_sequence(n)\nmodel.solve()\n\n# Print\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} +{"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_002_template_design", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob002_template_design.py", "# Source description: https://www.csplib.org/Problems/prob002/"], "description": "This problem arises from a colour printing firm which produces a variety of products from thin board, including cartons for human and animal food and magazine inserts. Food products, for example, are often marketed as a basic brand with several variations (typically flavours). Packaging for such variations usually has the same overall design, in particular the same size and shape, but differs in a small proportion of the text displayed and/or in colour. For instance, two variations of a cat food carton may differ only in that on one is printed ‘Chicken Flavour’ on a blue background whereas the other has ‘Rabbit Flavour’ printed on a green background. A typical order is for a variety of quantities of several design variations. Because each variation is identical in dimension, we know in advance exactly how many items can be printed on each mother sheet of board, whose dimensions are largely determined by the dimensions of the printing machinery. Each mother sheet is printed from a template, consisting of a thin aluminium sheet on which the design for several of the variations is etched. The problem is to decide, firstly, how many distinct templates to produce, and secondly, which variations, and how many copies of each, to include on each template. The given example is based on data from an order for cartons for different varieties of dry cat-food. Print the number of printed sheets (production) and the layout of the templates (layout).", "input_data": "n_slots = 9 # The amount of slots on a template n_templates = 2 # The amount of templates n_var = 7 # The amount of different variations demand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation", "model": "# Data\nn_slots = 9 # The amount of slots on a template\nn_templates = 2 # The amount of templates\nn_var = 7 # The amount of different variations\ndemand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Parameters\nub = max(demand) # The upper bound for the production\n\n# create model\nmodel = Model()\n\n# decision variables\nproduction = intvar(1, ub, shape=n_templates, name=\"production\")\nlayout = intvar(0, n_var, shape=(n_templates, n_var), name=\"layout\")\n\n# all slots are populated in a template\nmodel += all(sum(layout[i]) == n_slots for i in range(n_templates))\n\n# meet demand\nfor var in range(n_var):\n model += sum(production * layout[:, var]) >= demand[var]\n\n# break symmetry\n# equal demand\nfor i in range(n_var - 1):\n if demand[i] == demand[i + 1]:\n model += layout[0, i] <= layout[0, i + 1]\n for j in range(n_templates - 1):\n model += (layout[j, i] == layout[j, i + 1]).implies(layout[j + 1, i] <= layout[j + 1, i + 1])\n\n# distinguish templates\nfor i in range(n_templates - 1):\n model += production[i] <= production[i + 1]\n\n# static symmetry\nfor i in range(n_var - 1):\n if demand[i] < demand[i + 1]:\n model += sum(production * layout[:, i]) <= sum(production * layout[:, i + 1])\n\n# minimize number of printed sheets\nmodel.minimize(sum(production))\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"production\": production.value().tolist(), \"layout\": layout.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["production", "layout"]} +{"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_006_golomb_rules", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob006_golomb.py", "# Source description: https://www.csplib.org/Problems/prob006/"], "description": "These problems are said to have many practical applications including sensor placements for x-ray crystallography and radio astronomy. A Golomb ruler may be defined as a set of \\( m \\) integers \\( 0 = a_1 < a_2 < \\cdots < a_m \\) such that the \\( \\frac{m(m-1)}{2} \\) differences \\( a_j - a_i, \\, 1 \\leq i < j \\leq m \\) are distinct. Such a ruler is said to contain \\( m \\) marks and is of length \\( a_m \\). The objective is to find optimal (minimum length) or near-optimal rulers. Note that a symmetry can be removed by adding the constraint that \\( a_2 - a_1 < a_m - a_{m-1} \\), the first difference is less than the last. There is no requirement that a Golomb ruler measures all distances up to its length - the only requirement is that each distance is only measured in one way. However, if a ruler does measure all distances, it is classified as a perfect Golomb ruler. There exist several interesting generalizations of the problem which have received attention like modular Golomb rulers (differences are all distinct mod a given base), disjoint Golomb rulers, Golomb rectangles (the 2-dimensional generalization of Golomb rulers), and difference triangle sets (sets of rulers with no common difference). Print the positions of the marks (marks) and the total length of the Golomb ruler (length).", "input_data": "size = 10 # Number of marks on the Golomb ruler", "model": "# Data\nsize = 10 # Number of marks on the Golomb ruler\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\nmarks = intvar(0, size * size, shape=size, name=\"marks\")\nlength = marks[-1]\n\n# Model\nmodel = Model()\n\n# first mark is 0\nmodel += (marks[0] == 0)\n\n# marks must be increasing\nmodel += marks[:-1] < marks[1:]\n\n# golomb constraint\ndiffs = [marks[j] - marks[i] for i in range(0, size - 1) for j in range(i + 1, size)]\nmodel += AllDifferent(diffs)\n\n# Symmetry breaking\nmodel += (marks[size - 1] - marks[size - 2] > marks[1] - marks[0])\nmodel += (diffs[0] < diffs[size - 1])\n\n# find optimal ruler\nmodel.minimize(length)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"marks\": marks.value().tolist(), \"length\": length.value()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["marks", "length"]} +{"id": "csplib__csplib_007_all_interval", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob007_all_interval.py", "# Source description: https://www.csplib.org/Problems/prob007/"], "description": "Given the twelve standard pitch-classes (c, c#, d, …), represented by numbers \\(0, 1, \\ldots, 11\\), find a series in which each pitch-class occurs exactly once and in which the musical intervals between neighbouring notes cover the full set of intervals from the minor second (1 semitone) to the major seventh (11 semitones). That is, for each of the intervals, there is a pair of neighbouring pitch-classes in the series, between which this interval appears. The problem of finding such a series can be easily formulated as an instance of a more general arithmetic problem on \\(\\mathbb{Z}_n\\), the set of integer residues modulo \\(n\\). Given \\(n \\in \\mathbb{N}\\), find a vector \\(s = (s_1, \\ldots, s_n)\\), such that - \\(s\\) is a permutation of \\(\\mathbb{Z}_n = \\{0, 1, \\ldots, n-1\\}\\); and - the interval vector \\(v = (|s_2 - s_1|, |s_3 - s_2|, \\ldots, |s_n - s_{n-1}|)\\) is a permutation of \\(\\mathbb{Z}_n \\setminus \\{0\\} = \\{1, 2, \\ldots, n-1\\}\\). A vector \\(v\\) satisfying these conditions is called an all-interval series of size \\(n\\); the problem of finding such a series is the all-interval series problem of size \\(n\\). We may also be interested in finding all possible series of a given size. The All-Interval Series is a special case of the Graceful Graphs in which the graph is a line. Print the sequence of pitch-classes (x) and the corresponding intervals (diffs).", "input_data": "n = 12 # Number of pitch-classes", "model": "# Data\nn = 12 # Number of pitch-classes\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n# Create the solver\nmodel = Model()\n\n# Declare variables\nx = intvar(0, n - 1, shape=n, name=\"x\") # Pitch-classes\ndiffs = intvar(1, n - 1, shape=n - 1, name=\"diffs\") # Intervals\n\n# Constraints\nmodel += [AllDifferent(x),\n AllDifferent(diffs)]\n\n# Differences between successive values\nmodel += diffs == np.abs(x[1:] - x[:-1])\n\n# Symmetry breaking\nmodel += [x[0] < x[-1]] # Mirroring array is equivalent solution\nmodel += [diffs[0] < diffs[1]] # Further symmetry breaking\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\"x\": x.value().tolist(), \"diffs\": diffs.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["diffs", "x"]} +{"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_010_social_golfers_problem", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob010_social_golfers.py", "# Source description: https://www.csplib.org/Problems/prob010/"], "description": "The coordinator of a local golf club has come to you with the following problem. In their club, there are 32 social golfers, each of whom play golf once a week, and always in groups of 4. They would like you to come up with a schedule of play for these golfers, to last as many weeks as possible, such that no golfer plays in the same group as any other golfer on more than one occasion. Possible variants of the above problem include: finding a 10-week schedule with \"maximum socialisation\"; that is, as few repeated pairs as possible (this has the same solutions as the original problem if it is possible to have no repeated pairs), and finding a schedule of minimum length such that each golfer plays with every other golfer at least once (\"full socialisation\"). The problem can easily be generalized to that of scheduling \\( m \\) groups of \\( n \\) golfers over \\( p \\) weeks, such that no golfer plays in the same group as any other golfer twice (i.e. maximum socialisation is achieved). This problem is derived from a question posted to sci.op-research by bigwind777@aol.com (Bigwind777) in May 1998. It is a generalisation of the problem of constructing a round-robin tournament schedule, where the number of players in a \"game\" is more than two. The optimal solution for 32 golfers is not yet known. Print the assignments of golfers to groups for each week (assign).", "input_data": "n_weeks = 4 # Number of weeks n_groups = 3 # Number of groups group_size = 3 # Size of each group", "model": "# Data\nn_weeks = 4 # Number of weeks\nn_groups = 3 # Number of groups\ngroup_size = 3 # Size of each group\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\nimport numpy as np\nimport json\n\n\ndef social_golfers(n_weeks, n_groups, group_size):\n\n n_golfers = n_groups * group_size\n golfers = np.arange(n_golfers)\n weeks = np.arange(n_weeks)\n groups = np.arange(n_groups)\n\n # Possible configurations\n assign = intvar(0, n_groups - 1, shape=(n_golfers, n_weeks), name=\"assign\")\n\n model = Model()\n\n # C1: Each group has exactly group_size players\n for gr in groups:\n for w in weeks:\n model += sum(assign[:, w] == gr) == group_size\n\n # C2: Each pair of players only meets at most once\n for g1, g2 in all_pairs(golfers):\n model += sum(assign[g1] == assign[g2]) <= 1\n\n # SBSA: Symmetry-breaking by selective assignment\n # On the first week, the first group_size golfers play in group 1, the\n # second group_size golfers play in group 2, etc. On the second week,\n # golfer 1 plays in group 1, golfer 2 plays in group 2, etc.\n # model += [assign[:, 0] == (golfers // group_size)]\n\n for g in golfers:\n if g < group_size:\n model += [assign[g, 1] == g]\n\n # First golfer always in group 0\n model += [assign[0, :] == 0]\n\n return model, assign\n\n# Example usage\nmodel, assign = social_golfers(n_weeks, n_groups, group_size)\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"assign\": assign.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["assign"]} +{"id": "csplib__csplib_011_acc_basketball_schedule", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob011_basketball_schedule.py", "# Source description: https://www.csplib.org/Problems/prob011/"], "description": "The problem is finding a timetable for the 1997/98 Atlantic Coast Conference (ACC) in basketball. It was first tackled by Nemhauser and Trick. The 9 basketball teams in the tournament are Clemson (Clem), Duke (Duke), Florida State (FSU), Georgia Tech (GT), Maryland (UMD), North Carolina (UNC), North Carolina State (NCSt), Virginia (UVA), and Wake Forest (Wake). The problem is to determine a double round robin schedule for these 9 teams subject to some additional constraints. In a double round robin, each team plays each other, once at home, once away. The schedule is to be played over 18 dates. The first and all subsequent odd dates are weekday fixtures. The second and all subsequent even dates are weekend fixtures. There are nine other sets of constraints. 1. Mirroring. The dates are grouped into pairs (r1, r2), such that each team will get to play against the same team in dates r1 and r2. Such a grouping is called a mirroring scheme. Nemhauser and Trick use the mirroring scheme {(1, 8), (2, 9), (3, 12), (4, 13), (5, 14), (6, 15), (7, 16), (10, 17), (11, 18)} 2. No Two Final Aways. No team can play away on both last dates. 3. Home/Away/Bye Pattern Constraints. No team may have more than two away matches in a row. No team may have more than two home matches in a row. No team may have more than three away matches or byes in a row. No team may have more than four home matches or byes in a row. 4. Weekend Pattern. Of the weekends, each team plays four at home, four away, and one bye. 5. First Weekends. Each team must have home matches or byes at least on two of the first five weekends. 6. Rival Matches. Every team except FSU has a traditional rival. The rival pairs are Duke-UNC, Clem-GT, NCSt-Wake, and UMD-UVA. In the last date, every team except FSU plays against its rival, unless it plays against FSU or has a bye. 7. Constrained Matches. The following pairings must occur at least once in dates 11 to 18: Wake-UNC, Wake-Duke, GT-UNC, and GT-Duke. 8. Opponent Sequence Constraints. No team plays in two consecutive dates away against UNC and Duke. No team plays in three consecutive dates against UNC, Duke and Wake (independent of home/away). 9. Other Constraints. UNC plays its rival Duke in the last date and in date 11. UNC plays Clem in the second date. Duke has a bye in date 16. Wake does not play home in date 17. Wake has a bye in the first date. Clem, Duke, UMD and Wake do not play away in the last date. Clem, FSU, GT and Wake do not play away in the first date. Neither FSU nor NCSt have a bye in the last date. UNC does not have a bye in the first date. Print the match configuration (config) and whether the team is playing home, away, or has a bye (where).", "input_data": "n_teams = 9 n_days = 18", "model": "# Data\nn_teams = 9\nn_days = 18\n# End of data\n\n# Import libraries\nfrom cpmpy import *\nimport numpy as np\nimport json\n\n\ndef basketball_schedule():\n n_teams = 9\n n_days = 18\n\n # Teams\n teams = np.arange(n_teams)\n CLEM, DUKE, FSU, GT, UMD, UNC, NCSt, UVA, WAKE = teams\n rivals = [GT, UNC, FSU, CLEM, UVA, DUKE, WAKE, UMD, NCSt]\n\n # Days\n days = np.arange(n_days)\n weekdays = np.where(days % 2 == 0)[0]\n weekends = np.where(days % 2 == 1)[0]\n\n # matrix indicating which teams play against each other at what date\n # config[d,i] == j iff team i plays team j on day d of the tournament\n # config[d,i] == i iff team i plays bye on day d of the tournament\n config = intvar(0, n_teams - 1, shape=(n_days, n_teams), name=\"config\")\n # home[d,i] == True iff team i plays home on day d of the tournament\n where = intvar(0, 2, shape=(n_days, n_teams), name=\"where\")\n HOME, BYE, AWAY = 0, 1, 2\n\n model = Model()\n\n # a team cannot have different opponents on the same day\n for day_conf in config:\n model += AllDifferent(day_conf)\n\n # team plays itself when playing BYE\n for day in range(n_days):\n model += (config[day] == teams) == (where[day] == BYE)\n\n # symmetry\n for day in range(n_days):\n for t in range(n_teams):\n model += config[day, config[day, t]] == t\n\n # 1. mirroring constraint\n scheme = np.array([7, 8, 11, 12, 13, 14, 15, 0, 1, 16, 17, 2, 3, 4, 5, 6, 9, 10])\n model += config == config[scheme]\n model += where == (2 - where[scheme])\n\n # 2. no two final days away\n for t in range(n_teams):\n model += sum(where[-2:, t] == AWAY) <= 1\n\n # 3. home/away/bye pattern constraint\n for t in teams:\n for d in days[:-3]:\n # No team may have more than two home matches in a row\n model += sum(where[d:d + 3, t] == HOME) <= 2\n # No team may have more than two away matches in a row\n model += sum(where[d:d + 3, t] == AWAY) <= 2\n\n for d in days[:-4]:\n # No team may have more than three away matches or byes in a row\n model += sum((where[d:d + 4, t] == AWAY) |\n (where[d:d + 4, t] == BYE)) <= 3\n\n for d in days[:-5]:\n # No team may have more than four home matches or byes in a row.\n model += sum((where[d:d + 5, t] == HOME) |\n (where[d:d + 5, t] == BYE)) <= 4\n\n # 4. weekend pattern constraint\n # Of the weekends, each team plays four at home, four away, and one bye.\n for t in range(n_teams):\n model += sum(where[weekends, t] == HOME) == 4\n model += sum(where[weekends, t] == AWAY) == 4\n model += sum(where[weekends, t] == BYE) == 1\n\n # 5. first weekends constraint\n # Each team must have home matches or byes at least on two of the first five weekends.\n for t in range(n_teams):\n model += (sum(where[weekends[:5], t] == HOME) +\n sum(where[weekends[:5], t] == BYE)) >= 2\n\n # 6. rival matches constraint\n # In the last date, every team except FSU plays against its rival, unless it plays against FSU or has a bye.\n for t in teams:\n if t != FSU:\n model += (config[-1, t] == rivals[t]) | \\\n (config[-1, t] == FSU) | \\\n (where[-1, t] == BYE)\n\n # 7. Constrained matches\n # The following pairings must occur at least once in dates 11 to 18:\n # Wake-UNC, Wake-Duke, GT-UNC, and GT-Duke.\n model += sum(config[10:, WAKE] == UNC) >= 1\n model += sum(config[10:, WAKE] == DUKE) >= 1\n model += sum(config[10:, GT] == UNC) >= 1\n model += sum(config[10:, GT] == DUKE) >= 1\n\n # 8. Opponent Sequence constraints\n for t in teams:\n for d in days[:-2]:\n if t != DUKE and t != UNC:\n # No team plays in two consecutive dates away against UNC and Duke\n model += ((config[d, t] == UNC) & (where[d, t] == AWAY) &\n (config[d + 1, t] == DUKE) & (where[d + 1, t] == AWAY)).implies(False)\n model += ((config[d, t] == DUKE) & (where[d, t] == AWAY) &\n (config[d + 1, t] == UNC) & (where[d + 1, t] == AWAY)).implies(False)\n for d in days[:-3]:\n if t not in [UNC, DUKE, WAKE]:\n # No team plays in three consecutive dates against UNC, Duke and Wake (independent of home/away).\n model += ((config[d, t] == UNC) & (config[d + 1, t] == DUKE) & (config[d + 2, t] == WAKE)).implies(\n False)\n model += ((config[d, t] == UNC) & (config[d + 1, t] == WAKE) & (config[d + 2, t] == DUKE)).implies(\n False)\n model += ((config[d, t] == DUKE) & (config[d + 1, t] == UNC) & (config[d + 2, t] == WAKE)).implies(\n False)\n model += ((config[d, t] == DUKE) & (config[d + 1, t] == WAKE) & (config[d + 2, t] == UNC)).implies(\n False)\n model += ((config[d, t] == WAKE) & (config[d + 1, t] == UNC) & (config[d + 2, t] == DUKE)).implies(\n False)\n model += ((config[d, t] == WAKE) & (config[d + 1, t] == DUKE) & (config[d + 2, t] == UNC)).implies(\n False)\n\n # 9. Other constraints\n # UNC plays its rival Duke in the last date and in date 11\n model += config[10, UNC] == DUKE\n model += config[-1, UNC] == DUKE\n # UNC plays Clem in the second date\n model += config[1, UNC] == CLEM\n # Duke has a bye in date 16\n model += where[15, DUKE] == BYE\n # Wake does not play home in date 17\n model += where[16, WAKE] != HOME\n # Wake has a bye in the first date\n model += where[0, WAKE] == BYE\n # Clem, Duke, UMD and Wake do not play away in the last date\n model += where[-1, [CLEM, DUKE, UMD, WAKE]] != AWAY\n # Clem, FSU, GT and Wake do not play away in the first date\n model += where[0, [CLEM, FSU, GT, WAKE]] != AWAY\n # Neither FSU nor NCSt have a bye in last date\n model += where[-1, [FSU, NCSt]] != BYE\n # UNC does not have a bye in the first date.\n model += where[0, UNC] != BYE\n\n return model, (config, where)\n\n\n# Example usage\nmodel, (config, where) = basketball_schedule()\n\n# Solve\nmodel.solve()\n\n# Print\nsolution = {\n \"config\": config.value().tolist(),\n \"where\": where.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["config", "where"]} +{"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_013_progressive_party_problem", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob013_progressive_party.py", "# Source description: https://www.csplib.org/Problems/prob013/"], "description": "The problem is to timetable a party at a yacht club. Certain boats are to be designated hosts, and the crews of the remaining boats in turn visit the host boats for several successive half-hour periods. The crew of a host boat remains on board to act as hosts while the crew of a guest boat together visits several hosts. Every boat can only hold a limited number of people at a time (its capacity) and crew sizes are different. The total number of people aboard a boat, including the host crew and guest crews, must not exceed the capacity. A guest boat cannot not revisit a host and guest crews cannot meet more than once. The problem facing the rally organizer is that of minimizing the number of host boats. Print the visit schedule (visits) and the host designations (is_host).", "input_data": "n_boats = 5 # Number of boats n_periods = 4 # Number of periods capacity = [6, 8, 12, 12, 12] # Capacities of the boats crew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats", "model": "# Data\nn_boats = 5 # Number of boats\nn_periods = 4 # Number of periods\ncapacity = [6, 8, 12, 12, 12] # Capacities of the boats\ncrew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\n\ndef progressive_party(n_boats, n_periods, capacity, crew_size, **kwargs):\n is_host = boolvar(shape=n_boats, name=\"is_host\")\n visits = intvar(0, n_boats - 1, shape=(n_periods, n_boats), name=\"visits\")\n\n model = Model()\n\n # Crews of host boats stay on boat\n for boat in range(n_boats):\n model += (is_host[boat]).implies((visits[:, boat] == boat).all())\n\n # Number of visitors can never exceed capacity of boat\n for slot in range(n_periods):\n for boat in range(n_boats):\n model += sum((visits[slot] == boat) * crew_size) + crew_size[boat] * is_host[boat] <= capacity[boat]\n\n # Guests cannot visit a boat twice\n for boat in range(n_boats):\n model += (~is_host[boat]).implies(AllDifferent(visits[:, boat]))\n\n # Non-host boats cannot be visited\n for boat in range(n_boats):\n model += (~is_host[boat]).implies((visits != boat).all())\n\n # Crews cannot meet more than once\n for c1, c2 in all_pairs(range(n_boats)):\n model += sum(visits[:, c1] == visits[:, c2]) <= 1\n\n # Minimize number of hosts needed\n model.minimize(sum(is_host))\n\n return model, (visits, is_host)\n\n\n# Example usage\nmodel, (visits, is_host) = progressive_party(n_boats, n_periods, capacity, crew_size)\nmodel.solve()\n\n# Print\nsolution = {\n \"visits\": visits.value().tolist(),\n \"is_host\": is_host.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["is_host", "visits"]} +{"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_019_magic_squares_and_sequences", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob019_magic_sequence.py", "# Source description: https://www.csplib.org/Problems/prob019/"], "description": "An order \\( n \\) magic square is a \\( n \\) by \\( n \\) matrix containing the numbers 1 to \\( n^2 \\), with each row, column, and main diagonal equal to the same sum. As well as finding magic squares, we are interested in the number of a given size that exist. There are several interesting variations. For example, we may insist on certain values in certain squares (like in quasigroup completion) and ask if the magic square can be completed. In a heterosquare, each row, column, and diagonal sums to a different value. In an anti-magic square, the row, column, and diagonal sums form a sequence of consecutive integers. A magic sequence of length \\( n \\) is a sequence of integers \\( x_0, \\ldots, x_{n-1} \\) between 0 and \\( n-1 \\), such that for all \\( i \\) in 0 to \\( n-1 \\), the number \\( i \\) occurs exactly \\( x_i \\) times in the sequence. For instance, 6, 2, 1, 0, 0, 0, 1, 0, 0, 0 is a magic sequence since 0 occurs 6 times in it, 1 occurs twice, etc. Print the magic sequence (x).", "input_data": "n = 12 # Length of the magic sequence", "model": "# Data\nn = 12 # Length of the magic sequence\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef magic_sequence(n):\n model = Model()\n\n x = intvar(0, n - 1, shape=n, name=\"x\")\n\n # Constraints\n for i in range(n):\n model += x[i] == sum(x == i)\n\n # Speedup search\n model += sum(x) == n\n model += sum(x * np.arange(n)) == n\n\n return model, (x,)\n\n# Example usage\nmodel, (x,) = magic_sequence(n)\nmodel.solve()\n\n# Print\nsolution = {\"x\": x.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["x"]} {"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_024_langford", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob024_langford.py", "# Source description: https://www.csplib.org/Problems/prob024/"], "description": "024: Langford's Number Problem Consider two sets of the numbers from 1 to 4. The problem is to arrange the eight numbers in the two sets into a single sequence in which the two 1’s appear one number apart, the two 2’s appear two numbers apart, the two 3’s appear three numbers apart, and the two 4’s appear four numbers apart. The problem generalizes to the L(k, n) problem, which is to arrange k sets of numbers 1 to n, so that each appearance of the number m is m numbers on from the last. For example, the L(3, 9) problem is to arrange 3 sets of the numbers 1 to 9 so that the first two 1’s and the second two 1’s appear one number apart, the first two 2’s and the second two 2’s appear two numbers apart, etc. Print the positions (position) and the solution sequence (solution).", "input_data": "k = 4 # Number of sets", "model": "# Data\nk = 4 # Number of sets\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\n\n\ndef langford(k):\n model = Model()\n\n if not (k % 4 == 0 or k % 4 == 3):\n print(\"There is no solution for K unless K mod 4 == 0 or K mod 4 == 3\")\n return None, None\n\n # Variables\n position = intvar(0, 2 * k - 1, shape=2 * k, name=\"position\")\n solution = intvar(1, k, shape=2 * k, name=\"solution\")\n\n # Constraints\n model += [AllDifferent(position)]\n\n for i in range(1, k + 1):\n model += [position[i + k - 1] == position[i - 1] + i + 1]\n model += [i == solution[position[i - 1]]]\n model += [i == solution[position[k + i - 1]]]\n\n # Symmetry breaking\n model += [solution[0] < solution[2 * k - 1]]\n\n return model, (position, solution)\n\n\n# Example usage\nmodel, (position, solution) = langford(k)\nif model:\n model.solve()\n\n # Print\n solution_dict = {\n \"position\": position.value().tolist(),\n \"solution\": solution.value().tolist()\n }\n print(json.dumps(solution_dict))\n# End of CPMPy script", "decision_variables": ["position", "solution"]} -{"id": "csplib__csplib_026_sports_tournament_scheduling", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob026_sport_scheduling.py", "# Source description: https://www.csplib.org/Problems/prob026/"], "description": "026: Sports Tournament Scheduling The problem is to schedule a tournament of \\( n \\) teams over \\( n-1 \\) weeks, with each week divided into \\( n/2 \\) periods, and each period divided into two slots. The first team in each slot plays at home, whilst the second plays the first team away. A tournament must satisfy the following three constraints: every team plays once a week; every team plays at most twice in the same period over the tournament; every team plays every other team. An example schedule for 8 teams is: | Week 1 | Week 2 | Week 3 | Week 4 | Week 5 | Week 6 | Week 7 | |---------|---------|---------|---------|---------|---------|---------| | 0 v 1 | 0 v 2 | 4 v 7 | 3 v 6 | 3 v 7 | 1 v 5 | 2 v 4 | | 2 v 3 | 1 v 7 | 0 v 3 | 5 v 7 | 1 v 4 | 0 v 6 | 5 v 6 | | 4 v 5 | 3 v 5 | 1 v 6 | 0 v 4 | 2 v 6 | 2 v 7 | 0 v 7 | | 6 v 7 | 4 v 6 | 2 v 5 | 1 v 2 | 0 v 5 | 3 v 4 | 1 v 3 | One extension of the problem is to double round robin tournaments in which each team plays every other team (as before) but now both at home and away. This is often solved by repeating the round robin pattern, but swapping home games for away games in the repeat. Print the home and away schedules (home, away).", "input_data": "n_teams = 8 # Number of teams", "model": "# Data\nn_teams = 8 # Number of teams\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\nimport numpy as np\n\n\ndef sport_scheduling(n_teams):\n n_weeks, n_periods, n_matches = n_teams - 1, n_teams // 2, (n_teams - 1) * n_teams // 2\n\n home = intvar(1, n_teams, shape=(n_weeks, n_periods), name=\"home\")\n away = intvar(1, n_teams, shape=(n_weeks, n_periods), name=\"away\")\n\n model = Model()\n\n # teams cannot play each other\n model += home != away\n\n # every teams plays once a week\n # can be written cleaner, see issue #117\n # model += AllDifferent(np.append(home, away, axis=1), axis=0)\n for w in range(n_weeks):\n model += AllDifferent(np.append(home[w], away[w]))\n\n # every team plays each other\n for t1, t2 in all_pairs(range(1, n_teams + 1)):\n model += (sum((home == t1) & (away == t2)) + sum((home == t2) & (away == t1))) >= 1\n\n # every team plays at most twice in the same period\n for t in range(1, n_teams + 1):\n # can be written cleaner, see issue #117\n # sum((home == t) | (away == t), axis=1) <= 2\n for p in range(n_periods):\n model += sum((home[p] == t) | (away[p] == t)) <= 2\n\n return model, (home, away)\n\n\n# Example usage\nmodel, (home, away) = sport_scheduling(n_teams)\nmodel.solve()\n\n# Print\nsolution = {\n \"home\": home.value().tolist(),\n \"away\": away.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["home", "away"]} -{"id": "csplib__csplib_028_bibd", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob028_bibd.py", "# Source description: https://www.csplib.org/Problems/prob028/"], "description": "028: Balanced Incomplete Block Designs Balanced Incomplete Block Design (BIBD) generation is a standard combinatorial problem from design theory, originally used in the design of statistical experiments but since finding other applications such as cryptography. It is a special case of Block Design, which also includes Latin Square problems. BIBD generation is described in most standard textbooks on combinatorics. A BIBD is defined as an arrangement of \\( v \\) distinct objects into \\( b \\) blocks such that each block contains exactly \\( k \\) distinct objects, each object occurs in exactly \\( r \\) different blocks, and every two distinct objects occur together in exactly \\( \\lambda \\) blocks. Another way of defining a BIBD is in terms of its incidence matrix, which is a \\( v \\) by \\( b \\) binary matrix with exactly \\( r \\) ones per row, \\( k \\) ones per column, and with a scalar product of \\( \\lambda \\) between any pair of distinct rows. A BIBD is therefore specified by its parameters \\( (v, b, r, k, \\lambda) \\). An example of a solution for \\( (7, 7, 3, 3, 1) \\) is: 0 1 1 0 0 1 0 1 0 1 0 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 1 0 0 1 0 1 0 0 1 0 1 1 0 0 Lam’s problem is that of finding a BIBD with parameters \\( (111, 111, 11, 11, 1) \\). Print the incidence matrix of the BIBD (matrix).", "input_data": "v = 9 # Number of distinct objects b = 12 # Number of blocks r = 4 # Number of blocks each object occurs in k = 3 # Number of objects each block contains l = 1 # Number of blocks in which each pair of distinct objects occurs together", "model": "# Data\nv = 9 # Number of distinct objects\nb = 12 # Number of blocks\nr = 4 # Number of blocks each object occurs in\nk = 3 # Number of objects each block contains\nl = 1 # Number of blocks in which each pair of distinct objects occurs together\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 bibd(v, b, r, k, l):\n matrix = boolvar(shape=(v, b), name=\"matrix\")\n\n model = Model()\n\n # Every row adds up to r\n model += [sum(row) == r for row in matrix]\n # Every column adds up to k\n model += [sum(col) == k for col in matrix.T]\n\n # The scalar product of every pair of columns adds up to l\n model += [np.dot(row_i, row_j) == l for row_i, row_j in all_pairs(matrix)]\n\n # Break symmetry\n # Lexicographic ordering of rows\n for r in range(v - 1):\n bvar = boolvar(shape=(b + 1))\n model += bvar[0] == 1\n model += bvar == ((matrix[r] <= matrix[r + 1]) &\n ((matrix[r] < matrix[r + 1]) | (bvar[1:] == 1)))\n model += bvar[-1] == 0\n # Lexicographic ordering of columns\n for c in range(b - 1):\n bvar = boolvar(shape=(v + 1))\n model += bvar[0] == 1\n model += bvar == ((matrix.T[c] <= matrix.T[c + 1]) &\n ((matrix.T[c] < matrix.T[c + 1]) | (bvar[1:] == 1)))\n model += bvar[-1] == 0\n\n return model, (matrix,)\n\n# Example usage\nmodel, (matrix,) = bibd(v, b, r, k, l)\nmodel.solve()\n\n# Print\nsolution = {\"matrix\": matrix.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["matrix"]} -{"id": "csplib__csplib_033_word_design", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob033_word_design.py", "# Source description: https://www.csplib.org/Problems/prob033/"], "description": "033: Word Design for DNA Computing on Surfaces This problem has its roots in Bioinformatics and Coding Theory. Problem: find as large a set \\( S \\) of strings (words) of length 8 over the alphabet \\( W = \\{ A,C,G,T \\} \\) with the following properties: - Each word in \\( S \\) has 4 symbols from \\{ C,G \\}; - Each pair of distinct words in \\( S \\) differ in at least 4 positions; and - Each pair of words \\( x \\) and \\( y \\) in \\( S \\) (where \\( x \\) and \\( y \\) may be identical) are such that \\( x^R \\) and \\( y^C \\) differ in at least 4 positions. Here, \\( ( x_1,\\ldots,x_8 )^R = ( x_8,\\ldots,x_1 ) \\) is the reverse of \\( ( x_1,\\ldots,x_8 ) \\) and \\( ( y_1,\\ldots,y_8 )^C \\) is the Watson-Crick complement of \\( ( y_1,\\ldots,y_8 ) \\), i.e. the word where each \\( A \\) is replaced by a \\( T \\) and vice versa and each \\( C \\) is replaced by a \\( G \\) and vice versa. Print the set of words (words).", "input_data": "n = 8 # Number of words to find", "model": "# Data\nn = 8 # Number of words to find\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\ndef word_design(n=2):\n A, C, G, T = 1, 2, 3, 4\n\n # words[i,j] is the j'th letter of the i'th word\n words = intvar(A, T, shape=(n, 8), name=\"words\")\n\n model = Model()\n\n # 4 symbols from {C,G}\n for w in words:\n model += sum((w == C) | (w == G)) >= 4\n\n # Each pair of distinct words differ in at least 4 positions\n for x, y in all_pairs(words):\n model += (sum(x != y) >= 4)\n\n # Each pair of words x and y (where x and y may be identical)\n # are such that x^R and y^C differ in at least 4 positions\n for y in words:\n y_c = 5 - y # Watson-Crick complement\n for x in words:\n x_r = x[::-1] # reversed x\n model += sum(x_r != y_c) >= 4\n\n # Break symmetry\n for r in range(n - 1):\n b = boolvar(shape=(9,))\n model += b[0] == 1\n model += b == ((words[r] <= words[r + 1]) &\n ((words[r] < words[r + 1]) | (b[1:] == 1)))\n model += b[-1] == 0\n\n return model, (words,)\n\n# Example usage\nmodel, (words,) = word_design(n)\nmodel.solve()\n\n# Print\nsolution = {\"words\": words.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["words"]} -{"id": "csplib__csplib_044_steiner", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob044_steiner.py", "# Source description: https://www.csplib.org/Problems/prob044/"], "description": "044: Steiner Triple Systems The ternary Steiner problem of order \\( n \\) consists of finding a set of \\( n \\cdot (n-1)/6 \\) triples of distinct integer elements in \\(\\{1, \\ldots, n\\}\\) such that any two triples have at most one common element. It is a hypergraph problem coming from combinatorial mathematics [luneburg1989tools] where \\( n \\) modulo 6 has to be equal to 1 or 3 [lindner2011topics]. One possible solution for \\( n = 7 \\) is \\(\\{\\{1, 2, 3\\}, \\{1, 4, 5\\}, \\{1, 6, 7\\}, \\{2, 4, 6\\}, \\{2, 5, 7\\}, \\{3, 4, 7\\}, \\{3, 5, 6\\}\\}\\). The solution contains \\( 7 \\cdot (7-1)/6 = 7 \\) triples. This is a particular case of the more general Steiner system. More generally still, you may refer to Balanced Incomplete Block Designs. In fact, a Steiner Triple System with \\( n \\) elements is a BIBD(\\( n, n \\cdot (n-1)/6, (n-1)/2, 3, 1 \\)). Print the set of triples (sets).", "input_data": "n = 9 # Order of the Steiner Triple System", "model": "# Data\nn = 9 # Order of the Steiner Triple System\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\ndef steiner(n=15):\n assert n % 6 == 1 or n % 6 == 3, \"N must be (1|3) modulo 6\"\n\n n_sets = int(n * (n - 1) // 6)\n\n model = Model()\n\n # boolean representation of sets\n # sets[i,j] = true iff item j is part of set i\n sets = boolvar(shape=(n_sets, n), name=\"sets\")\n\n # cardinality of set if 3\n # can be written cleaner, see issue #117\n # model += sum(sets, axis=0) == 3\n model += [sum(s) == 3 for s in sets]\n\n # cardinality of intersection <= 1\n for s1, s2 in all_pairs(sets):\n model += sum(s1 & s2) <= 1\n\n # symmetry breaking\n model += (sets[(0, 0)] == 1)\n\n return model, (sets,)\n\n# Example usage\nmodel, (sets,) = steiner(n)\nmodel.solve()\n\n# Print\nsolution = {\"sets\": sets.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["sets"]} -{"id": "csplib__csplib_049_number_partitioning", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob049_number_partitioning.py", "# Source description: https://www.csplib.org/Problems/prob049/"], "description": "049: Number Partitioning This problem consists in finding a partition of numbers 1..N into two sets A and B such that: - A and B have the same cardinality - Sum of numbers in A = sum of numbers in B - Sum of squares of numbers in A = sum of squares of numbers in B There is no solution for \\( N < 8 \\). Here is an example for \\( N = 8 \\): A = (1, 4, 6, 7) and B = (2, 3, 5, 8) From \\( N \\geq 8 \\), there is no solution if \\( N \\) is not a multiple of 4. Print the sets A and B (A, B).", "input_data": "n = 12 # The number N", "model": "# Data\nn = 12 # The number N\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef number_partitioning(n=8):\n assert n % 2 == 0, \"The value of n must be even\"\n\n # x[i] is the ith value of the first set\n x = intvar(1, n, shape=n // 2)\n\n # y[i] is the ith value of the second set\n y = intvar(1, n, shape=n // 2)\n\n model = Model()\n\n model += AllDifferent(np.append(x, y))\n\n # sum of numbers is equal in both sets\n model += sum(x) == sum(y)\n\n # sum of squares is equal in both sets\n model += sum(x ** 2) == sum(y ** 2)\n\n # break symmetry\n model += x[:-1] <= x[1:]\n model += y[:-1] <= x[1:]\n\n return model, (x,y)\n\n# Example usage\nmodel, (x, y) = number_partitioning(n)\nmodel.solve()\n\nA = x\nB = y\n\n# Print\nsolution = {\"A\": x.value().tolist(), \"B\": y.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["A", "B"]} -{"id": "csplib__csplib_050_diamond_free", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob050_diamond_free.py", "# Source description: https://www.csplib.org/Problems/prob050/"], "description": "050: Diamond-free Degree Sequences Given a simple undirected graph \\( G = (V, E) \\), where \\( V \\) is the set of vertices and \\( E \\) the set of undirected edges, the edge \\(\\{u, v\\}\\) is in \\( E \\) if and only if vertex \\( u \\) is adjacent to vertex \\( v \\in G \\). The graph is simple in that there are no loop edges, i.e., we have no edges of the form \\(\\{v, v\\}\\). Each vertex \\( v \\in V \\) has a degree \\( d_v \\) i.e., the number of edges incident on that vertex. Consequently, a graph has a degree sequence \\( d_1, \\ldots, d_n \\), where \\( d_i \\geq d_{i+1} \\). A diamond is a set of four vertices in \\( V \\) such that there are at least five edges between those vertices. Conversely, a graph is diamond-free if it has no diamond as an induced subgraph, i.e., for every set of four vertices the number of edges between those vertices is at most four. In our problem, we have additional properties required of the degree sequences of the graphs, in particular, that the degree of each vertex is greater than zero (i.e., isolated vertices are disallowed), the degree of each vertex is modulo 3, and the sum of the degrees is modulo 12 (i.e., \\(|E|\\) is modulo 6). The problem is then for a given value of \\( n \\), produce all unique degree sequences \\( d_1, \\ldots, d_n \\) such that - \\( d_i \\geq d_{i+1} \\) - Each degree \\( d_i > 0 \\) and \\( d_i \\) is modulo 3 - The sum of the degrees is modulo 12 - There exists a simple diamond-free graph with that degree sequence Print the adjacency matrix of the graph (matrix).", "input_data": "N = 10 # Number of vertices in the graph", "model": "# Data\nN = 10 # Number of vertices in the graph\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\nfrom itertools import combinations\n\ndef diamond_free(N=10):\n # By definition a and b will have the same cardinality:\n matrix = boolvar(shape=(N, N), name=\"matrix\")\n\n model = Model()\n\n # No rows contain just zeroes.\n model += [sum(row) > 0 for row in matrix] # can be written cleaner, see issue #117\n # Every row has a sum modulo 3.\n model += [sum(row) % 3 == 0 for row in matrix]\n # The sum of the matrix is modulo 12.\n model += sum(matrix) % 12 == 0\n # No row R contains a 1 in its Rth column.\n model += [matrix[np.diag_indices(N)] == 0]\n\n # Every grouping of 4 rows can have at most a sum of 4 between them.\n for a, b, c, d in combinations(range(N), 4):\n model += sum([matrix[a][b], matrix[a][c], matrix[a][d],\n matrix[b][c], matrix[b][d], matrix[c][d]]) <= 4\n\n # Undirected graph\n model += matrix == matrix.T\n\n # Symmetry breaking\n # lexicographic ordering of rows\n for r in range(N - 1):\n b = boolvar(N + 1)\n model += b[0] == 1\n model += b == ((matrix[r] <= matrix[r + 1]) &\n ((matrix[r] < matrix[r + 1]) | b[1:] == 1))\n model += b[-1] == 0\n # lexicographic ordering of cols\n for c in range(N - 1):\n b = boolvar(N + 1)\n model += b[0] == 1\n model += b == ((matrix.T[c] <= matrix.T[c + 1]) &\n ((matrix.T[c] < matrix.T[c + 1]) | b[1:] == 1))\n model += b[-1] == 0\n\n return model, matrix\n\n# Example usage\nmodel, matrix = diamond_free(N)\nmodel.solve()\n\n# Print\nsolution = {\"matrix\": matrix.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["matrix"]} -{"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": "053: Graceful Graphs 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_054_n_queens", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob054_n_queens.py", "# Source description: https://www.csplib.org/Problems/prob054/"], "description": "054: N-Queens Problem Can \\( n \\) queens (of the same color) be placed on a \\( n \\times n \\) chessboard so that none of the queens can attack each other? In chess, a queen attacks other squares on the same row, column, or either diagonal as itself. So the \\( n \\)-queens problem is to find a set of \\( n \\) locations on a chessboard, no two of which are on the same row, column or diagonal. A simple arithmetical observation may be helpful in understanding models. Suppose a queen is represented by an ordered pair \\((\\alpha, \\beta)\\), the value \\(\\alpha\\) represents the queen’s column, and \\(\\beta\\) its row on the chessboard. Then two queens do not attack each other iff they have different values of all of \\(\\alpha\\), \\(\\beta\\), \\(\\alpha - \\beta\\), and \\(\\alpha + \\beta\\). It may not be intuitively obvious that chessboard diagonals correspond to sums and differences, but consider moving one square along the two orthogonal diagonals: in one direction the sum of the coordinates does not change, while in the other direction the difference does not change. (We do not suggest that pairs \\((\\alpha, \\beta)\\) is a good representation for solving.) The problem has inherent symmetry. That is, for any solution we obtain another solution by any of the 8 symmetries of the chessboard (including the identity) obtained by combinations of rotations by 90 degrees and reflections. Print the positions of the queens on the chessboard (queens).", "input_data": "n = 10 # Size of the chessboard and number of queens", "model": "# Data\nn = 10 # Size of the chessboard and number of queens\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef n_queens(n=8):\n\n queens = intvar(1, n, shape=n, name=\"queens\")\n\n # Constraints on columns and left/right diagonal\n model = Model([\n AllDifferent(queens),\n AllDifferent(queens - np.arange(n)),\n AllDifferent(queens + np.arange(n)),\n ])\n\n return model, (queens,)\n\n# Example usage\nmodel, (queens,) = n_queens(n)\nmodel.solve()\n\n# Print\nsolution = {\"queens\": queens.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["queens"]} -{"id": "csplib__csplib_076_costas_arrays", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob076_costas_arrays.py", "# Source description: https://www.csplib.org/Problems/prob076/"], "description": "076: Costas Array A Costas array is a pattern of \\( n \\) marks on an \\( n \\times n \\) grid, one mark per row and one per column, in which the \\( n \\cdot (n-1)/2 \\) vectors between the marks are all different. Such patterns are important as they provide a template for generating radar and sonar signals with ideal ambiguity functions. A model for Costas Array Problem (CAP) is to define an array of variables \\( X_1, \\ldots, X_n \\) which form a permutation. For each length \\( l \\in \\{1, \\ldots, n-1\\} \\), we add \\( n-l \\) more variables \\( X_{l1}, \\ldots, X_{ln-1} \\), whereby each of these variables is assigned the difference of \\( X_i - X_{i+l} \\) for \\( i \\in \\{1, \\ldots, n-l\\} \\). These additional variables form a difference triangle. Each line of this difference triangle must not contain any value twice. That is, the CAP is simply a collection of all-different constraints on \\( X_1, \\ldots, X_n \\) and \\( X_{l1}, \\ldots, X_{ln-l} \\) for all \\( l \\in \\{1, \\ldots, n-1\\} \\). Print the Costas array (costas).", "input_data": "n = 8 # Size of the Costas array", "model": "# Data\nn = 8 # Size of the Costas array\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef costas_array(n=6):\n model = Model()\n\n # Declare variables\n costas = intvar(1, n, shape=n, name=\"costas\")\n differences = intvar(-n + 1, n - 1, shape=(n, n), name=\"differences\")\n\n tril_idx = np.tril_indices(n, -1)\n triu_idx = np.triu_indices(n, 1)\n\n # Constraints\n # Fix the values in the lower triangle in the difference matrix to -n+1.\n model += differences[tril_idx] == -n + 1\n\n model += [AllDifferent(costas)]\n\n # Define the differences\n for i, j in zip(*triu_idx):\n model += [differences[i, j] == costas[j] - costas[j - i - 1]]\n\n # All entries in a particular row of the difference triangle must be distinct\n for i in range(n - 2):\n model += [AllDifferent([differences[i, j] for j in range(n) if j > i])]\n\n # Additional constraints to speed up the search\n model += differences[triu_idx] != 0\n for k, l in zip(*triu_idx):\n if k < 2 or l < 2:\n continue\n model += [differences[k - 2, l - 1] + differences[k, l] ==\n differences[k - 1, l - 1] + differences[k - 1, l]]\n\n return model, (costas, differences)\n\n# Example usage\nmodel, (costas, differences) = costas_array(n)\nmodel.solve()\n\n# Print\nsolution = {\n \"costas\": costas.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["costas"]} -{"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": "084: 2cc Hadamard Matrix Legendre Pairs 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": "csplib__csplib_024_langford", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob024_langford.py", "# Source description: https://www.csplib.org/Problems/prob024/"], "description": "Consider two sets of the numbers from 1 to 4. The problem is to arrange the eight numbers in the two sets into a single sequence in which the two 1’s appear one number apart, the two 2’s appear two numbers apart, the two 3’s appear three numbers apart, and the two 4’s appear four numbers apart. The problem generalizes to the L(k, n) problem, which is to arrange k sets of numbers 1 to n, so that each appearance of the number m is m numbers on from the last. For example, the L(3, 9) problem is to arrange 3 sets of the numbers 1 to 9 so that the first two 1’s and the second two 1’s appear one number apart, the first two 2’s and the second two 2’s appear two numbers apart, etc. Print the positions (position) and the solution sequence (solution).", "input_data": "k = 4 # Number of sets", "model": "# Data\nk = 4 # Number of sets\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\n\n\ndef langford(k):\n model = Model()\n\n if not (k % 4 == 0 or k % 4 == 3):\n print(\"There is no solution for K unless K mod 4 == 0 or K mod 4 == 3\")\n return None, None\n\n # Variables\n position = intvar(0, 2 * k - 1, shape=2 * k, name=\"position\")\n solution = intvar(1, k, shape=2 * k, name=\"solution\")\n\n # Constraints\n model += [AllDifferent(position)]\n\n for i in range(1, k + 1):\n model += [position[i + k - 1] == position[i - 1] + i + 1]\n model += [i == solution[position[i - 1]]]\n model += [i == solution[position[k + i - 1]]]\n\n # Symmetry breaking\n model += [solution[0] < solution[2 * k - 1]]\n\n return model, (position, solution)\n\n\n# Example usage\nmodel, (position, solution) = langford(k)\nif model:\n model.solve()\n\n # Print\n solution_dict = {\n \"position\": position.value().tolist(),\n \"solution\": solution.value().tolist()\n }\n print(json.dumps(solution_dict))\n# End of CPMPy script", "decision_variables": ["position", "solution"]} +{"id": "csplib__csplib_026_sports_tournament_scheduling", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob026_sport_scheduling.py", "# Source description: https://www.csplib.org/Problems/prob026/"], "description": "The problem is to schedule a tournament of \\( n \\) teams over \\( n-1 \\) weeks, with each week divided into \\( n/2 \\) periods, and each period divided into two slots. The first team in each slot plays at home, whilst the second plays the first team away. A tournament must satisfy the following three constraints: every team plays once a week; every team plays at most twice in the same period over the tournament; every team plays every other team. An example schedule for 8 teams is: | Week 1 | Week 2 | Week 3 | Week 4 | Week 5 | Week 6 | Week 7 | |---------|---------|---------|---------|---------|---------|---------| | 0 v 1 | 0 v 2 | 4 v 7 | 3 v 6 | 3 v 7 | 1 v 5 | 2 v 4 | | 2 v 3 | 1 v 7 | 0 v 3 | 5 v 7 | 1 v 4 | 0 v 6 | 5 v 6 | | 4 v 5 | 3 v 5 | 1 v 6 | 0 v 4 | 2 v 6 | 2 v 7 | 0 v 7 | | 6 v 7 | 4 v 6 | 2 v 5 | 1 v 2 | 0 v 5 | 3 v 4 | 1 v 3 | One extension of the problem is to double round robin tournaments in which each team plays every other team (as before) but now both at home and away. This is often solved by repeating the round robin pattern, but swapping home games for away games in the repeat. Print the home and away schedules (home, away).", "input_data": "n_teams = 8 # Number of teams", "model": "# Data\nn_teams = 8 # Number of teams\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\nimport numpy as np\n\n\ndef sport_scheduling(n_teams):\n n_weeks, n_periods, n_matches = n_teams - 1, n_teams // 2, (n_teams - 1) * n_teams // 2\n\n home = intvar(1, n_teams, shape=(n_weeks, n_periods), name=\"home\")\n away = intvar(1, n_teams, shape=(n_weeks, n_periods), name=\"away\")\n\n model = Model()\n\n # teams cannot play each other\n model += home != away\n\n # every teams plays once a week\n # can be written cleaner, see issue #117\n # model += AllDifferent(np.append(home, away, axis=1), axis=0)\n for w in range(n_weeks):\n model += AllDifferent(np.append(home[w], away[w]))\n\n # every team plays each other\n for t1, t2 in all_pairs(range(1, n_teams + 1)):\n model += (sum((home == t1) & (away == t2)) + sum((home == t2) & (away == t1))) >= 1\n\n # every team plays at most twice in the same period\n for t in range(1, n_teams + 1):\n # can be written cleaner, see issue #117\n # sum((home == t) | (away == t), axis=1) <= 2\n for p in range(n_periods):\n model += sum((home[p] == t) | (away[p] == t)) <= 2\n\n return model, (home, away)\n\n\n# Example usage\nmodel, (home, away) = sport_scheduling(n_teams)\nmodel.solve()\n\n# Print\nsolution = {\n \"home\": home.value().tolist(),\n \"away\": away.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["home", "away"]} +{"id": "csplib__csplib_028_bibd", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob028_bibd.py", "# Source description: https://www.csplib.org/Problems/prob028/"], "description": "Balanced Incomplete Block Design (BIBD) generation is a standard combinatorial problem from design theory, originally used in the design of statistical experiments but since finding other applications such as cryptography. It is a special case of Block Design, which also includes Latin Square problems. BIBD generation is described in most standard textbooks on combinatorics. A BIBD is defined as an arrangement of \\( v \\) distinct objects into \\( b \\) blocks such that each block contains exactly \\( k \\) distinct objects, each object occurs in exactly \\( r \\) different blocks, and every two distinct objects occur together in exactly \\( \\lambda \\) blocks. Another way of defining a BIBD is in terms of its incidence matrix, which is a \\( v \\) by \\( b \\) binary matrix with exactly \\( r \\) ones per row, \\( k \\) ones per column, and with a scalar product of \\( \\lambda \\) between any pair of distinct rows. A BIBD is therefore specified by its parameters \\( (v, b, r, k, \\lambda) \\). An example of a solution for \\( (7, 7, 3, 3, 1) \\) is: 0 1 1 0 0 1 0 1 0 1 0 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 1 0 0 1 0 1 0 0 1 0 1 1 0 0 Lam’s problem is that of finding a BIBD with parameters \\( (111, 111, 11, 11, 1) \\). Print the incidence matrix of the BIBD (matrix).", "input_data": "v = 9 # Number of distinct objects b = 12 # Number of blocks r = 4 # Number of blocks each object occurs in k = 3 # Number of objects each block contains l = 1 # Number of blocks in which each pair of distinct objects occurs together", "model": "# Data\nv = 9 # Number of distinct objects\nb = 12 # Number of blocks\nr = 4 # Number of blocks each object occurs in\nk = 3 # Number of objects each block contains\nl = 1 # Number of blocks in which each pair of distinct objects occurs together\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 bibd(v, b, r, k, l):\n matrix = boolvar(shape=(v, b), name=\"matrix\")\n\n model = Model()\n\n # Every row adds up to r\n model += [sum(row) == r for row in matrix]\n # Every column adds up to k\n model += [sum(col) == k for col in matrix.T]\n\n # The scalar product of every pair of columns adds up to l\n model += [np.dot(row_i, row_j) == l for row_i, row_j in all_pairs(matrix)]\n\n # Break symmetry\n # Lexicographic ordering of rows\n for r in range(v - 1):\n bvar = boolvar(shape=(b + 1))\n model += bvar[0] == 1\n model += bvar == ((matrix[r] <= matrix[r + 1]) &\n ((matrix[r] < matrix[r + 1]) | (bvar[1:] == 1)))\n model += bvar[-1] == 0\n # Lexicographic ordering of columns\n for c in range(b - 1):\n bvar = boolvar(shape=(v + 1))\n model += bvar[0] == 1\n model += bvar == ((matrix.T[c] <= matrix.T[c + 1]) &\n ((matrix.T[c] < matrix.T[c + 1]) | (bvar[1:] == 1)))\n model += bvar[-1] == 0\n\n return model, (matrix,)\n\n# Example usage\nmodel, (matrix,) = bibd(v, b, r, k, l)\nmodel.solve()\n\n# Print\nsolution = {\"matrix\": matrix.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["matrix"]} +{"id": "csplib__csplib_033_word_design", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob033_word_design.py", "# Source description: https://www.csplib.org/Problems/prob033/"], "description": "This problem has its roots in Bioinformatics and Coding Theory. Problem: find as large a set \\( S \\) of strings (words) of length 8 over the alphabet \\( W = \\{ A,C,G,T \\} \\) with the following properties: - Each word in \\( S \\) has 4 symbols from \\{ C,G \\}; - Each pair of distinct words in \\( S \\) differ in at least 4 positions; and - Each pair of words \\( x \\) and \\( y \\) in \\( S \\) (where \\( x \\) and \\( y \\) may be identical) are such that \\( x^R \\) and \\( y^C \\) differ in at least 4 positions. Here, \\( ( x_1,\\ldots,x_8 )^R = ( x_8,\\ldots,x_1 ) \\) is the reverse of \\( ( x_1,\\ldots,x_8 ) \\) and \\( ( y_1,\\ldots,y_8 )^C \\) is the Watson-Crick complement of \\( ( y_1,\\ldots,y_8 ) \\), i.e. the word where each \\( A \\) is replaced by a \\( T \\) and vice versa and each \\( C \\) is replaced by a \\( G \\) and vice versa. Print the set of words (words).", "input_data": "n = 8 # Number of words to find", "model": "# Data\nn = 8 # Number of words to find\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\ndef word_design(n=2):\n A, C, G, T = 1, 2, 3, 4\n\n # words[i,j] is the j'th letter of the i'th word\n words = intvar(A, T, shape=(n, 8), name=\"words\")\n\n model = Model()\n\n # 4 symbols from {C,G}\n for w in words:\n model += sum((w == C) | (w == G)) >= 4\n\n # Each pair of distinct words differ in at least 4 positions\n for x, y in all_pairs(words):\n model += (sum(x != y) >= 4)\n\n # Each pair of words x and y (where x and y may be identical)\n # are such that x^R and y^C differ in at least 4 positions\n for y in words:\n y_c = 5 - y # Watson-Crick complement\n for x in words:\n x_r = x[::-1] # reversed x\n model += sum(x_r != y_c) >= 4\n\n # Break symmetry\n for r in range(n - 1):\n b = boolvar(shape=(9,))\n model += b[0] == 1\n model += b == ((words[r] <= words[r + 1]) &\n ((words[r] < words[r + 1]) | (b[1:] == 1)))\n model += b[-1] == 0\n\n return model, (words,)\n\n# Example usage\nmodel, (words,) = word_design(n)\nmodel.solve()\n\n# Print\nsolution = {\"words\": words.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["words"]} +{"id": "csplib__csplib_044_steiner", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob044_steiner.py", "# Source description: https://www.csplib.org/Problems/prob044/"], "description": "The ternary Steiner problem of order \\( n \\) consists of finding a set of \\( n \\cdot (n-1)/6 \\) triples of distinct integer elements in \\(\\{1, \\ldots, n\\}\\) such that any two triples have at most one common element. It is a hypergraph problem coming from combinatorial mathematics [luneburg1989tools] where \\( n \\) modulo 6 has to be equal to 1 or 3 [lindner2011topics]. One possible solution for \\( n = 7 \\) is \\(\\{\\{1, 2, 3\\}, \\{1, 4, 5\\}, \\{1, 6, 7\\}, \\{2, 4, 6\\}, \\{2, 5, 7\\}, \\{3, 4, 7\\}, \\{3, 5, 6\\}\\}\\). The solution contains \\( 7 \\cdot (7-1)/6 = 7 \\) triples. This is a particular case of the more general Steiner system. More generally still, you may refer to Balanced Incomplete Block Designs. In fact, a Steiner Triple System with \\( n \\) elements is a BIBD(\\( n, n \\cdot (n-1)/6, (n-1)/2, 3, 1 \\)). Print the set of triples (sets).", "input_data": "n = 9 # Order of the Steiner Triple System", "model": "# Data\nn = 9 # Order of the Steiner Triple System\n# End of data\n\n# Import libraries\nimport json\nfrom cpmpy import *\nfrom cpmpy.expressions.utils import all_pairs\n\ndef steiner(n=15):\n assert n % 6 == 1 or n % 6 == 3, \"N must be (1|3) modulo 6\"\n\n n_sets = int(n * (n - 1) // 6)\n\n model = Model()\n\n # boolean representation of sets\n # sets[i,j] = true iff item j is part of set i\n sets = boolvar(shape=(n_sets, n), name=\"sets\")\n\n # cardinality of set if 3\n # can be written cleaner, see issue #117\n # model += sum(sets, axis=0) == 3\n model += [sum(s) == 3 for s in sets]\n\n # cardinality of intersection <= 1\n for s1, s2 in all_pairs(sets):\n model += sum(s1 & s2) <= 1\n\n # symmetry breaking\n model += (sets[(0, 0)] == 1)\n\n return model, (sets,)\n\n# Example usage\nmodel, (sets,) = steiner(n)\nmodel.solve()\n\n# Print\nsolution = {\"sets\": sets.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["sets"]} +{"id": "csplib__csplib_049_number_partitioning", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob049_number_partitioning.py", "# Source description: https://www.csplib.org/Problems/prob049/"], "description": "This problem consists in finding a partition of numbers 1..N into two sets A and B such that: - A and B have the same cardinality - Sum of numbers in A = sum of numbers in B - Sum of squares of numbers in A = sum of squares of numbers in B There is no solution for \\( N < 8 \\). Here is an example for \\( N = 8 \\): A = (1, 4, 6, 7) and B = (2, 3, 5, 8) From \\( N \\geq 8 \\), there is no solution if \\( N \\) is not a multiple of 4. Print the sets A and B (A, B).", "input_data": "n = 12 # The number N", "model": "# Data\nn = 12 # The number N\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef number_partitioning(n=8):\n assert n % 2 == 0, \"The value of n must be even\"\n\n # x[i] is the ith value of the first set\n x = intvar(1, n, shape=n // 2)\n\n # y[i] is the ith value of the second set\n y = intvar(1, n, shape=n // 2)\n\n model = Model()\n\n model += AllDifferent(np.append(x, y))\n\n # sum of numbers is equal in both sets\n model += sum(x) == sum(y)\n\n # sum of squares is equal in both sets\n model += sum(x ** 2) == sum(y ** 2)\n\n # break symmetry\n model += x[:-1] <= x[1:]\n model += y[:-1] <= x[1:]\n\n return model, (x,y)\n\n# Example usage\nmodel, (x, y) = number_partitioning(n)\nmodel.solve()\n\nA = x\nB = y\n\n# Print\nsolution = {\"A\": x.value().tolist(), \"B\": y.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["A", "B"]} +{"id": "csplib__csplib_050_diamond_free", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob050_diamond_free.py", "# Source description: https://www.csplib.org/Problems/prob050/"], "description": "Given a simple undirected graph \\( G = (V, E) \\), where \\( V \\) is the set of vertices and \\( E \\) the set of undirected edges, the edge \\(\\{u, v\\}\\) is in \\( E \\) if and only if vertex \\( u \\) is adjacent to vertex \\( v \\in G \\). The graph is simple in that there are no loop edges, i.e., we have no edges of the form \\(\\{v, v\\}\\). Each vertex \\( v \\in V \\) has a degree \\( d_v \\) i.e., the number of edges incident on that vertex. Consequently, a graph has a degree sequence \\( d_1, \\ldots, d_n \\), where \\( d_i \\geq d_{i+1} \\). A diamond is a set of four vertices in \\( V \\) such that there are at least five edges between those vertices. Conversely, a graph is diamond-free if it has no diamond as an induced subgraph, i.e., for every set of four vertices the number of edges between those vertices is at most four. In our problem, we have additional properties required of the degree sequences of the graphs, in particular, that the degree of each vertex is greater than zero (i.e., isolated vertices are disallowed), the degree of each vertex is modulo 3, and the sum of the degrees is modulo 12 (i.e., \\(|E|\\) is modulo 6). The problem is then for a given value of \\( n \\), produce all unique degree sequences \\( d_1, \\ldots, d_n \\) such that - \\( d_i \\geq d_{i+1} \\) - Each degree \\( d_i > 0 \\) and \\( d_i \\) is modulo 3 - The sum of the degrees is modulo 12 - There exists a simple diamond-free graph with that degree sequence Print the adjacency matrix of the graph (matrix).", "input_data": "N = 10 # Number of vertices in the graph", "model": "# Data\nN = 10 # Number of vertices in the graph\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\nfrom itertools import combinations\n\ndef diamond_free(N=10):\n # By definition a and b will have the same cardinality:\n matrix = boolvar(shape=(N, N), name=\"matrix\")\n\n model = Model()\n\n # No rows contain just zeroes.\n model += [sum(row) > 0 for row in matrix] # can be written cleaner, see issue #117\n # Every row has a sum modulo 3.\n model += [sum(row) % 3 == 0 for row in matrix]\n # The sum of the matrix is modulo 12.\n model += sum(matrix) % 12 == 0\n # No row R contains a 1 in its Rth column.\n model += [matrix[np.diag_indices(N)] == 0]\n\n # Every grouping of 4 rows can have at most a sum of 4 between them.\n for a, b, c, d in combinations(range(N), 4):\n model += sum([matrix[a][b], matrix[a][c], matrix[a][d],\n matrix[b][c], matrix[b][d], matrix[c][d]]) <= 4\n\n # Undirected graph\n model += matrix == matrix.T\n\n # Symmetry breaking\n # lexicographic ordering of rows\n for r in range(N - 1):\n b = boolvar(N + 1)\n model += b[0] == 1\n model += b == ((matrix[r] <= matrix[r + 1]) &\n ((matrix[r] < matrix[r + 1]) | b[1:] == 1))\n model += b[-1] == 0\n # lexicographic ordering of cols\n for c in range(N - 1):\n b = boolvar(N + 1)\n model += b[0] == 1\n model += b == ((matrix.T[c] <= matrix.T[c + 1]) &\n ((matrix.T[c] < matrix.T[c + 1]) | b[1:] == 1))\n model += b[-1] == 0\n\n return model, matrix\n\n# Example usage\nmodel, matrix = diamond_free(N)\nmodel.solve()\n\n# Print\nsolution = {\"matrix\": matrix.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["matrix"]} +{"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_054_n_queens", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob054_n_queens.py", "# Source description: https://www.csplib.org/Problems/prob054/"], "description": "Can \\( n \\) queens (of the same color) be placed on a \\( n \\times n \\) chessboard so that none of the queens can attack each other? In chess, a queen attacks other squares on the same row, column, or either diagonal as itself. So the \\( n \\)-queens problem is to find a set of \\( n \\) locations on a chessboard, no two of which are on the same row, column or diagonal. A simple arithmetical observation may be helpful in understanding models. Suppose a queen is represented by an ordered pair \\((\\alpha, \\beta)\\), the value \\(\\alpha\\) represents the queen’s column, and \\(\\beta\\) its row on the chessboard. Then two queens do not attack each other iff they have different values of all of \\(\\alpha\\), \\(\\beta\\), \\(\\alpha - \\beta\\), and \\(\\alpha + \\beta\\). It may not be intuitively obvious that chessboard diagonals correspond to sums and differences, but consider moving one square along the two orthogonal diagonals: in one direction the sum of the coordinates does not change, while in the other direction the difference does not change. (We do not suggest that pairs \\((\\alpha, \\beta)\\) is a good representation for solving.) The problem has inherent symmetry. That is, for any solution we obtain another solution by any of the 8 symmetries of the chessboard (including the identity) obtained by combinations of rotations by 90 degrees and reflections. Print the positions of the queens on the chessboard (queens).", "input_data": "n = 10 # Size of the chessboard and number of queens", "model": "# Data\nn = 10 # Size of the chessboard and number of queens\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef n_queens(n=8):\n\n queens = intvar(1, n, shape=n, name=\"queens\")\n\n # Constraints on columns and left/right diagonal\n model = Model([\n AllDifferent(queens),\n AllDifferent(queens - np.arange(n)),\n AllDifferent(queens + np.arange(n)),\n ])\n\n return model, (queens,)\n\n# Example usage\nmodel, (queens,) = n_queens(n)\nmodel.solve()\n\n# Print\nsolution = {\"queens\": queens.value().tolist()}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["queens"]} +{"id": "csplib__csplib_076_costas_arrays", "category": "csplib", "metadata": ["#!/usr/bin/python3", "# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob076_costas_arrays.py", "# Source description: https://www.csplib.org/Problems/prob076/"], "description": "A Costas array is a pattern of \\( n \\) marks on an \\( n \\times n \\) grid, one mark per row and one per column, in which the \\( n \\cdot (n-1)/2 \\) vectors between the marks are all different. Such patterns are important as they provide a template for generating radar and sonar signals with ideal ambiguity functions. A model for Costas Array Problem (CAP) is to define an array of variables \\( X_1, \\ldots, X_n \\) which form a permutation. For each length \\( l \\in \\{1, \\ldots, n-1\\} \\), we add \\( n-l \\) more variables \\( X_{l1}, \\ldots, X_{ln-1} \\), whereby each of these variables is assigned the difference of \\( X_i - X_{i+l} \\) for \\( i \\in \\{1, \\ldots, n-l\\} \\). These additional variables form a difference triangle. Each line of this difference triangle must not contain any value twice. That is, the CAP is simply a collection of all-different constraints on \\( X_1, \\ldots, X_n \\) and \\( X_{l1}, \\ldots, X_{ln-l} \\) for all \\( l \\in \\{1, \\ldots, n-1\\} \\). Print the Costas array (costas).", "input_data": "n = 8 # Size of the Costas array", "model": "# Data\nn = 8 # Size of the Costas array\n# End of data\n\n# Import libraries\nimport json\nimport numpy as np\nfrom cpmpy import *\n\ndef costas_array(n=6):\n model = Model()\n\n # Declare variables\n costas = intvar(1, n, shape=n, name=\"costas\")\n differences = intvar(-n + 1, n - 1, shape=(n, n), name=\"differences\")\n\n tril_idx = np.tril_indices(n, -1)\n triu_idx = np.triu_indices(n, 1)\n\n # Constraints\n # Fix the values in the lower triangle in the difference matrix to -n+1.\n model += differences[tril_idx] == -n + 1\n\n model += [AllDifferent(costas)]\n\n # Define the differences\n for i, j in zip(*triu_idx):\n model += [differences[i, j] == costas[j] - costas[j - i - 1]]\n\n # All entries in a particular row of the difference triangle must be distinct\n for i in range(n - 2):\n model += [AllDifferent([differences[i, j] for j in range(n) if j > i])]\n\n # Additional constraints to speed up the search\n model += differences[triu_idx] != 0\n for k, l in zip(*triu_idx):\n if k < 2 or l < 2:\n continue\n model += [differences[k - 2, l - 1] + differences[k, l] ==\n differences[k - 1, l - 1] + differences[k - 1, l]]\n\n return model, (costas, differences)\n\n# Example usage\nmodel, (costas, differences) = costas_array(n)\nmodel.solve()\n\n# Print\nsolution = {\n \"costas\": costas.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["costas"]} +{"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"]} @@ -81,21 +81,21 @@ {"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__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__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__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__exodus", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/exodus.mzn"], "description": "In preparation for Passover, five children at Hebrew school (Bernice, Carl, Debby, Sammy, and Ted) have been chosen to present different parts of the story of the Exodus from Egypt (burning bush, captivity, Moses’s youth, Passover, or the Ten Commandments). Each child is a different age (three, five, seven, eight, or ten), and the family of each child has recently made its own exodus to America from a different country (Ethiopia, Kazakhstan, Lithuania, Morocco, or Yemen). Can you find the age of each child, his or her family’s country of origin, and the part of the Exodus story each related? 1. Debby’s family is from Lithuania. 2. The child who told the story of the Passover is two years older than Bernice. 3. The child whose family is from Yemen is younger than the child from the Ethiopian family. 4. The child from the Moroccan family is three years older than Ted. 5. Sammy is three years older than the child who told the story of Moses’s youth in the house of the Pharaoh. Determine the association: Age-Child-Country-Story. Print the ages (ages), children (children), countries (countries), and stories (stories) as lists of integers from 1 to 5, where the same number represents a mapping between the four categories.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\n# We model the ages, children, countries, and stories as integer variables with values from 1 to 5.\nage3, age5, age7, age8, age10 = ages = intvar(1, 5, shape=5)\nbernice, carl, debby, sammy, ted = children = intvar(1, 5, shape=5)\nethiopia, kazakhstan, lithuania, morocco, yemen = countries = intvar(1, 5, shape=5)\nburning_bush, captivity, moses_youth, passover, ten_commandments = stories = intvar(1, 5, shape=5)\n\n# Constraints\nmodel = Model()\n\n# All entities are different per category\nmodel += AllDifferent(ages)\nmodel += AllDifferent(children)\nmodel += AllDifferent(countries)\nmodel += AllDifferent(stories)\n\n# Debby’s family is from Lithuania.\nmodel += debby == lithuania\n\n# The child who told the story of the Passover is two years older than Bernice.\n# So, we will add constraints for all possible pairs of ages to enforce this relationship.\nage_to_int = {age3: 3, age5: 5, age7: 7, age8: 8, age10: 10}\nmodel += [((a1 == passover) & (a2 == bernice)).implies(age_to_int[a1] == age_to_int[a2] + 2)\n for a1 in ages for a2 in ages]\n\n# The child whose family is from Yemen is younger than the child from the Ethiopian family.\nmodel += [((a1 == yemen) & (a2 == ethiopia)).implies(age_to_int[a1] < age_to_int[a2])\n for a1 in ages for a2 in ages]\n\n# The child from the Moroccan family is three years older than Ted.\nmodel += [((a1 == morocco) & (a2 == ted)).implies(age_to_int[a1] == age_to_int[a2] + 3)\n for a1 in ages for a2 in ages]\n\n# Sammy is three years older than the child who told the story of Moses’s youth in the house of the Pharaoh.\nmodel += [((a1 == sammy) & (a2 == moses_youth)).implies(age_to_int[a1] == age_to_int[a2] + 3)\n for a1 in ages for a2 in ages]\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"ages\": ages.value().tolist(),\n \"children\": children.value().tolist(),\n \"countries\": countries.value().tolist(),\n \"stories\": stories.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["countries", "children", "stories", "ages"]} -{"id": "aplai_course__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__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__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__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__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__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__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__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__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__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__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__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__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__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"]} +{"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_exodus", "category": "aplai_course", "metadata": ["#!/usr/bin/python3", "# Source: http://www.hakank.org/minizinc/exodus.mzn"], "description": "In preparation for Passover, five children at Hebrew school (Bernice, Carl, Debby, Sammy, and Ted) have been chosen to present different parts of the story of the Exodus from Egypt (burning bush, captivity, Moses’s youth, Passover, or the Ten Commandments). Each child is a different age (three, five, seven, eight, or ten), and the family of each child has recently made its own exodus to America from a different country (Ethiopia, Kazakhstan, Lithuania, Morocco, or Yemen). Can you find the age of each child, his or her family’s country of origin, and the part of the Exodus story each related? 1. Debby’s family is from Lithuania. 2. The child who told the story of the Passover is two years older than Bernice. 3. The child whose family is from Yemen is younger than the child from the Ethiopian family. 4. The child from the Moroccan family is three years older than Ted. 5. Sammy is three years older than the child who told the story of Moses’s youth in the house of the Pharaoh. Determine the association: Age-Child-Country-Story. Print the ages (ages), children (children), countries (countries), and stories (stories) as lists of integers from 1 to 5, where the same number represents a mapping between the four categories.", "input_data": "", "model": "# Import libraries\nfrom cpmpy import *\nimport json\n\n# Decision variables\n# We model the ages, children, countries, and stories as integer variables with values from 1 to 5.\nage3, age5, age7, age8, age10 = ages = intvar(1, 5, shape=5)\nbernice, carl, debby, sammy, ted = children = intvar(1, 5, shape=5)\nethiopia, kazakhstan, lithuania, morocco, yemen = countries = intvar(1, 5, shape=5)\nburning_bush, captivity, moses_youth, passover, ten_commandments = stories = intvar(1, 5, shape=5)\n\n# Constraints\nmodel = Model()\n\n# All entities are different per category\nmodel += AllDifferent(ages)\nmodel += AllDifferent(children)\nmodel += AllDifferent(countries)\nmodel += AllDifferent(stories)\n\n# Debby’s family is from Lithuania.\nmodel += debby == lithuania\n\n# The child who told the story of the Passover is two years older than Bernice.\n# So, we will add constraints for all possible pairs of ages to enforce this relationship.\nage_to_int = {age3: 3, age5: 5, age7: 7, age8: 8, age10: 10}\nmodel += [((a1 == passover) & (a2 == bernice)).implies(age_to_int[a1] == age_to_int[a2] + 2)\n for a1 in ages for a2 in ages]\n\n# The child whose family is from Yemen is younger than the child from the Ethiopian family.\nmodel += [((a1 == yemen) & (a2 == ethiopia)).implies(age_to_int[a1] < age_to_int[a2])\n for a1 in ages for a2 in ages]\n\n# The child from the Moroccan family is three years older than Ted.\nmodel += [((a1 == morocco) & (a2 == ted)).implies(age_to_int[a1] == age_to_int[a2] + 3)\n for a1 in ages for a2 in ages]\n\n# Sammy is three years older than the child who told the story of Moses’s youth in the house of the Pharaoh.\nmodel += [((a1 == sammy) & (a2 == moses_youth)).implies(age_to_int[a1] == age_to_int[a2] + 3)\n for a1 in ages for a2 in ages]\n\n# Solve\nmodel.solve()\n\n# Print the solution\nsolution = {\n \"ages\": ages.value().tolist(),\n \"children\": children.value().tolist(),\n \"countries\": countries.value().tolist(),\n \"stories\": stories.value().tolist()\n}\nprint(json.dumps(solution))\n# End of CPMPy script", "decision_variables": ["countries", "children", "stories", "ages"]} +{"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"]}