diff --git "a/template_submission.jsonl" "b/template_submission.jsonl" new file mode 100644--- /dev/null +++ "b/template_submission.jsonl" @@ -0,0 +1,101 @@ +{"id": "csplib__csplib_001_car_sequencing", "model": "from cpmpy import *\nimport json\n\n# Data\nat_most = [1, 2, 2, 2, 1]\nper_slots = [2, 3, 3, 5, 5]\ndemand = [1, 1, 2, 2, 2, 2]\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]]\n\n# Model\nn_cars = sum(demand)\nn_properties = len(at_most)\nn_types = len(demand)\n\n# Variables\nsequence = intvar(0, n_types-1, shape=n_cars, name=\"sequence\")\n\n# Constraints\nmodel = Model()\nfor t in range(n_types):\n model += sum([sequence[i] == t for i in range(n_cars)]) == demand[t]\n\nfor p in range(n_properties):\n for i in range(n_cars - per_slots[p] + 1):\n model += sum([requires[sequence[j]][p] for j in range(i, i + per_slots[p])]) <= at_most[p]\n\n# Solve\nif model.solve():\n # Get the solution\n solution = [sequence[i].value() for i in range(n_cars)]\n\n # Print the solution as a JSON object\n print(json.dumps({\"sequence\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_002_template_design", "model": "from cpmpy import *\nimport json\n\n# Data\nn_slots = 9\nn_templates = 2\nn_var = 7\ndemand = [250, 255, 260, 500, 500, 800, 1100]\n\n# Variables\ntemplates = intvar(0, n_templates, shape=n_var, name=\"templates\")\nnum_sheets = intvar(0, 10000, name=\"num_sheets\")\nproduction = intvar(0, 10000, name=\"production\")\nlayout = intvar(0, n_var, shape=(n_templates, n_slots), name=\"layout\")\n\n# Model\nmodel = Model(\n [AllDifferent(templates)],\n [\n production == sum([sum([layout[t, s] for s in range(n_slots)]) for t in range(n_templates)]),\n num_sheets == production,\n [sum([layout[t, s] for t in range(n_templates) for s in range(n_slots) if templates[s] == v]) == demand[v] for v in range(n_var)],\n [sum([layout[t, s] for s in range(n_slots)]) <= n_slots for t in range(n_templates)],\n ]\n)\n\n# Solve\nif model.solve():\n solution = {\n \"production\": production.value(),\n \"layout\": [[layout[t, s].value() for s in range(n_slots)] for t in range(n_templates)],\n }\n print(json.dumps(solution, indent=4))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_005_autocorrelation", "model": "from cpmpy import *\nimport numpy as np\nimport json\n\nn = 10\n\n# Model\ns = boolvar(shape=n, name=\"s\")\n\n# Convert bool to +/- 1\ns_int = [2 * s[i] - 1 for i in range(n)]\n\n# Compute autocorrelations\nC = []\nfor k in range(1, n):\n C_k = sum([s_int[i] * s_int[(i + k) % n] for i in range(n)])\n C.append(C_k)\n\n# Objective: minimize sum of squares of autocorrelations\nE = sum([C_k**2 for C_k in C])\n\n# Model\nmodel = Model(minimize=E)\n\n# Solve\nif model.solve():\n sequence = [int(s_i) for s_i in s.value()]\n sequence = [2 * s_i - 1 for s_i in sequence] # Convert to +/- 1\n E_val = E.value()\n print(json.dumps({\"sequence\": sequence, \"E\": E_val}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_006_golomb_rules", "model": "from cpmpy import *\nimport json\n\n# Data\nsize = 10\n\n# Model\nmarks = intvar(0, 1000, shape=size, name=\"marks\")\nlength = intvar(0, 1000, name=\"length\")\n\n# Constraints\nmodel = Model(\n [marks[i] < marks[i+1] for i in range(size-1)], # marks are in increasing order\n [length == marks[-1]], # length of the ruler is the last mark\n [AllDifferent([marks[j] - marks[i] for i in range(size) for j in range(i+1, size)])], # all differences are distinct\n [marks[1] - marks[0] < marks[-1] - marks[-2]] # symmetry breaking constraint\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\n \"marks\": [int(m.value()) for m in marks],\n \"length\": int(length.value())\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_007_all_interval", "model": "from cpmpy import *\nimport json\n\nn = 12\n\n# Decision variable: permutation of pitch-classes\nx = intvar(0, n-1, shape=n, name=\"x\")\n\n# Decision variable: intervals between pitch-classes\ndiffs = intvar(1, n-1, shape=n-1, name=\"diffs\")\n\n# Model\nmodel = Model(\n # x is a permutation of pitch-classes\n AllDifferent(x),\n\n # diffs are the intervals between pitch-classes\n [diffs[i] == abs(x[i+1] - x[i]) for i in range(n-1)],\n\n # diffs are a permutation of intervals from 1 to n-1\n AllDifferent(diffs)\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"diffs\": [diffs[i].value() for i in range(n-1)],\n \"x\": [x[i].value() for i in range(n)]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_008_vessel_loading", "model": "from cpmpy import *\nimport json\n\n# Data\ndeck_width = 5\ndeck_length = 5\nn_containers = 3\nwidth = [5, 2, 3]\nlength = [1, 4, 4]\nclasses = [1, 1, 1]\nseparation = [\n [0, 0],\n [0, 0]\n]\n\n# Variables\nx = intvar(0, deck_length, shape=n_containers, name=\"x\")\ny = intvar(0, deck_width, shape=n_containers, name=\"y\")\n\n# Model\nmodel = Model()\n\n# Constraints\nfor i in range(n_containers):\n model += [x[i] + length[i] <= deck_length]\n model += [y[i] + width[i] <= deck_width]\n\nfor i in range(n_containers):\n for j in range(i+1, n_containers):\n model += [x[i] + length[i] <= x[j] or x[j] + length[j] <= x[i]]\n model += [y[i] + width[i] <= y[j] or y[j] + width[j] <= y[i]]\n\nfor i in range(n_containers):\n for j in range(i+1, n_containers):\n if classes[i] != classes[j]:\n model += [abs(x[i] - x[j]) >= separation[classes[i]-1][classes[j]-1]]\n model += [abs(y[i] - y[j]) >= separation[classes[i]-1][classes[j]-1]]\n\n# Additional constraints for loading sequence\nfor i in range(1, n_containers):\n model += [x[i] >= x[i-1]]\n model += [y[i] >= y[i-1]]\n\n# Solve\nstatus = model.solve()\n\n# Print solution\nif status:\n left = [x[i].value() for i in range(n_containers)]\n right = [x[i].value() + length[i] for i in range(n_containers)]\n top = [y[i].value() + width[i] for i in range(n_containers)]\n bottom = [y[i].value() for i in range(n_containers)]\n solution = {\n \"left\": left,\n \"right\": right,\n \"top\": top,\n \"bottom\": bottom\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_009_perfect_square_placement", "model": "from cpmpy import *\nimport json\n\n# Data\nbase = 6\nsides = [3, 3, 3, 2, 1, 1, 1, 1, 1]\n\n# Model\nx_coords = intvar(0, base, shape=len(sides), name=\"x_coords\")\ny_coords = intvar(0, base, shape=len(sides), name=\"y_coords\")\nsquare_sizes = [side**2 for side in sides]\n\nmodel = Model(\n [x_coords[i] + sides[i] <= base for i in range(len(sides))],\n [y_coords[i] + sides[i] <= base for i in range(len(sides))],\n [x_coords[i] + sides[i] <= x_coords[j] or x_coords[j] + sides[j] <= x_coords[i] or \n y_coords[i] + sides[i] <= y_coords[j] or y_coords[j] + sides[j] <= y_coords[i] \n for i in range(len(sides)) for j in range(i+1, len(sides))],\n [sum([square_sizes[i] for i in range(len(sides))]) == base**2]\n)\n\n# Solve\nif model.solve():\n solution = {\n \"x_coords\": x_coords.value(),\n \"y_coords\": y_coords.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_010_social_golfers_problem", "model": "from cpmpy import *\nimport json\n\n# Data\nn_weeks = 4\nn_groups = 3\ngroup_size = 3\nn_golfers = n_groups * group_size\n\n# Model\ngolfer = intvar(0, n_golfers-1, shape=(n_weeks, n_groups, group_size))\nassign = boolvar(shape=(n_weeks, n_groups, group_size, n_golfers), name=\"assign\")\n\n# Constraints\nmodel = Model()\n\n# Each golfer plays once per week\nfor w in range(n_weeks):\n for g in range(n_golfers):\n model += sum([assign[w, group, pos, g] for group in range(n_groups) for pos in range(group_size)]) == 1\n\n# Each group has the correct size\nfor w in range(n_weeks):\n for group in range(n_groups):\n model += sum([assign[w, group, pos, g] for pos in range(group_size) for g in range(n_golfers)]) == group_size\n\n# No golfer plays in the same group twice\nfor g1 in range(n_golfers):\n for g2 in range(g1+1, n_golfers):\n model += sum([assign[w, group, pos1, g1] * assign[w, group, pos2, g2] for w in range(n_weeks) for group in range(n_groups) for pos1 in range(group_size) for pos2 in range(group_size)]) <= 1\n\n# Link golfer and assign\nfor w in range(n_weeks):\n for group in range(n_groups):\n for pos in range(group_size):\n model += golfer[w, group, pos] == sum([g * assign[w, group, pos, g] for g in range(n_golfers)])\n\n# Solve\nif model.solve():\n # Extract solution\n assign_sol = assign.value()\n solution = {\n \"assign\": [[[int(assign_sol[w, group, pos, g]) for g in range(n_golfers)] for pos in range(group_size)] for group in range(n_groups) for w in range(n_weeks)]\n }\n print(json.dumps(solution, indent=2))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_011_acc_basketball_schedule", "model": "from cpmpy import *\nimport json\n\n# Data\nn_teams = 9\nn_days = 18\nteams = range(n_teams)\ndays = range(n_days)\nmirroring_scheme = [(1, 8), (2, 9), (3, 12), (4, 13), (5, 14), (6, 15), (7, 16), (10, 17), (11, 18)]\nrivals = {0: 1, 1: 0, 2: 3, 3: 2, 4: 5, 5: 4, 6: 7, 7: 6}\nconstrained_matches = [(8, 1), (8, 0), (3, 1), (3, 0)]\n\n# Variables\nconfig = intvar(0, n_teams-1, shape=(n_teams, n_days), name=\"config\")\nwhere = intvar(0, 2, shape=(n_teams, n_days), name=\"where\")\n\n# Constraints\nmodel = Model()\n\n# Each team plays each other team once at home and once away\nfor i in teams:\n for j in teams:\n if i != j:\n model += sum([where[i, k] == 0 for k in days if config[i, k] == j]) == 1\n model += sum([where[j, k] == 0 for k in days if config[j, k] == i]) == 1\n\n# Each team plays each other team once at home and once away\nfor i in teams:\n for j in teams:\n if i != j:\n model += sum([where[i, k] == 1 for k in days if config[i, k] == j]) == 1\n model += sum([where[j, k] == 1 for k in days if config[j, k] == i]) == 1\n\n# No team can play away on both last dates\nfor i in teams:\n model += where[i, n_days-2] + where[i, n_days-1] <= 1\n\n# Home/Away/Bye Pattern Constraints\nfor i in teams:\n for j in range(n_days-2):\n model += where[i, j] + where[i, j+1] + where[i, j+2] <= 2\n model += (2 - where[i, j]) + (2 - where[i, j+1]) + (2 - where[i, j+2]) <= 2\n model += where[i, j] + where[i, j+1] + where[i, j+2] + (1 - where[i, j+3]) <= 3\n model += (2 - where[i, j]) + (2 - where[i, j+1]) + (2 - where[i, j+2]) + (2 - where[i, j+3]) <= 4\n\n# Weekend Pattern\nweekends = [1, 3, 5, 7, 9, 11, 13, 15, 17]\nfor i in teams:\n model += sum([where[i, k] == 0 for k in weekends]) == 4\n model += sum([where[i, k] == 1 for k in weekends]) == 4\n model += sum([where[i, k] == 2 for k in weekends]) == 1\n\n# First Weekends\nfor i in teams:\n model += sum([where[i, k] == 0 for k in weekends[:5]]) + sum([where[i, k] == 2 for k in weekends[:5]]) >= 2\n\n# Rival Matches\nfor i in teams:\n if i in rivals:\n model += config[i, n_days-1] == rivals[i]\n\n# Constrained Matches\nfor match in constrained_matches:\n model += sum([config[i, k] == match[1] for i, k in zip([match[0]], range(10, n_days))]) >= 1\n\n# Opponent Sequence Constraints\nfor i in teams:\n for j in range(n_days-2):\n model += where[i, j] + where[i, j+1] <= 1 if config[i, j] in [0, 1] and config[i, j+1] in [0, 1] else 1\n model += where[i, j] + where[i, j+1] + where[i, j+2] <= 2 if config[i, j] in [0, 1, 8] and config[i, j+1] in [0, 1, 8] and config[i, j+2] in [0, 1, 8] else 1\n\n# Other Constraints\nmodel += config[1, n_days-1] == 0\nmodel += config[1, 10] == 0\nmodel += where[1, 1] == 0\nmodel += config[2, 1] == 1\nmodel += where[0, 15] == 2\nmodel += where[8, 16] == 2\nmodel += where[2, 0] == 2\nmodel += where[0, n_days-1] == 0\nmodel += where[2, n_days-1] == 0\nmodel += where[6, n_days-1] == 0\nmodel += where[8, n_days-1] == 0\nmodel += where[4, 0] == 0\nmodel += where[3, 0] == 0\nmodel += where[2, 0] == 0\nmodel += where[8, 0] == 0\nmodel += where[5, n_days-1] == 1\nmodel += where[7, n_days-1] == 1\nmodel += where[1, 0] == 1\n\n# Solve\nif model.solve():\n config_sol = config.value()\n where_sol = where.value()\n output = {\"config\": config_sol, \"where\": where_sol}\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_012_nonogram", "model": "from cpmpy import *\nimport json\n\n# Data\nrows = 8\nrow_rule_len = 2\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]\n\ncols = 13\ncol_rule_len = 2\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]\n\n# Model\nboard = boolvar(shape=(rows, cols), name=\"board\")\n\nmodel = Model()\n\n# Row constraints\nfor i in range(rows):\n row = [board[i, j] for j in range(cols)]\n model += [LengthGeq(row, row_rules[i])]\n\n# Column constraints\nfor j in range(cols):\n col = [board[i, j] for i in range(rows)]\n model += [LengthGeq(col, col_rules[j])]\n\n# Solve\nif model.solve():\n solution = [[int(board[i, j].value()) for j in range(cols)] for i in range(rows)]\n print(json.dumps({\"board\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_013_progressive_party_problem", "model": "from cpmpy import *\nimport json\n\n# Data\nn_boats = 5\nn_periods = 4\ncapacity = [6, 8, 12, 12, 12]\ncrew_size = [2, 2, 2, 2, 4]\n\n# Variables\nis_host = boolvar(shape=n_boats, name=\"is_host\")\nvisits = intvar(lb=0, ub=n_boats-1, shape=(n_boats, n_periods), name=\"visits\")\n\n# Model\nmodel = Model(\n # Objective: minimize number of host boats\n Minimize(sum(is_host)),\n\n # Constraints\n [is_host[visits[i, j]] for i in range(n_boats) for j in range(n_periods)], # visit a host\n [visits[i, j] != visits[i, k] for i in range(n_boats) for j in range(n_periods) for k in range(j+1, n_periods)], # don't revisit\n [sum([crew_size[i] for i in range(n_boats) if visits[i, j] == h]) + crew_size[h] <= capacity[h] for h in range(n_boats) for j in range(n_periods)], # capacity constraint\n [visits[i, j] != visits[k, j] for i in range(n_boats) for k in range(i+1, n_boats) for j in range(n_periods)] # don't meet twice\n)\n\n# Solve\nif model.solve():\n # Get solution\n is_host_sol = [is_host[i].value() for i in range(n_boats)]\n visits_sol = [[visits[i, j].value() for j in range(n_periods)] for i in range(n_boats)]\n\n # Output as JSON\n output = {\n \"is_host\": is_host_sol,\n \"visits\": visits_sol\n }\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_015_schurs_lemma", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 13 # Number of balls\nc = 3 # Number of boxes\n\n# Variables\nM = boolvar((n, c), name=\"M\")\n\n# Constraints\nconstraints = [\n [sum(M[i]) == 1 for i in range(n)], # Each ball is in exactly one box\n [M[x, j] + M[y, j] + M[z, j] <= 2 \n for x in range(1, n+1) \n for y in range(1, n+1) \n for z in range(1, n+1) \n for j in range(c) \n if x + y == z and x < y] # Not all balls in a triple are in the same box\n]\n\n# Model\nmodel = Model(constraints)\n\n# Solve\nif model.solve():\n # Get the assignment of balls to boxes\n balls = [next((j+1 for j, val in enumerate(row) if val.value()), None) for row in M]\n\n # Print the solution as a JSON object\n print(json.dumps({\"balls\": balls}))\nelse:\n print(\"No solution found.\")"} +{"id": "csplib__csplib_019_magic_squares_and_sequences", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 12\n\n# Model\nx = intvar(0, n, shape=n, name=\"x\")\n\n# Constraints\nmodel = Model(\n [sum(x) == n], # The length of the sequence is n\n [sum([x[j] for j in range(n) if j == i]) == x[i] for i in range(n)] # Each number i occurs x_i times\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\"x\": [val for val in x.value()]}\n print(json.dumps(solution, indent=4))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_021_crossfigures", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nM = []\nfor i in range(9):\n row = []\n for j in range(9):\n if (i, j) in [(1, 2), (1, 7), (2, 2), (2, 4), (2, 6), (2, 8), (3, 1), (3, 3), (3, 5), (3, 7), (4, 0), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 8), (5, 1), (5, 3), (5, 7), (6, 1), (6, 3), (6, 5), (6, 7), (7, 0), (7, 2), (7, 5), (7, 7), (8, 1), (8, 3), (8, 5), (8, 7)]:\n row.append(model.int_var(0, 999))\n else:\n row.append(model.int_var(0, 999, name=f\"M_{i}_{j}\"))\n M.append(row)\n\n# Define the constraints\nmodel += [M[0][0] == 27 * M[0][8] * 2]\nmodel += [M[0][3] == M[3][0] + 71]\nmodel += [M[0][6] == M[5][1] + 4]\nmodel += [M[0][7] == M[2][5] / 16]\nmodel += [M[0][8] == M[1][1] - 18]\nmodel += [M[1][9] == 12 * 6]\nmodel += [M[2][0] == M[0][4] - 70]\nmodel += [M[3][2] == M[1][7] * M[0][2]]\nmodel += [M[3][4] == M[2][5] - 350]\nmodel += [M[4][0] == M[0][8] * M[0][2]]\nmodel += [M[5][3] >= 0] # Square number\nmodel += [M[5][3] == M[5][3] ** 2]\nmodel += [M[5][6] >= 0] # Square number\nmodel += [M[5][6] == M[5][6] ** 2]\nmodel += [M[6][0] == M[5][3] / 17]\nmodel += [M[6][2] == M[2][5] / 4]\nmodel += [M[6][7] == 4 * 12]\nmodel += [M[7][1] == 7 * 12 * 12]\nmodel += [M[8][3] == M[5][7] + 450]\nmodel += [M[1][0] == M[0][0] + 27]\nmodel += [M[1][1] == 5 * 12]\nmodel += [M[2][0] == M[5][7] + 888]\nmodel += [M[3][0] == 2 * M[4][0]]\nmodel += [M[4][1] == M[7][1] / 12]\nmodel += [M[5][0] == M[6][7] * M[0][2]]\nmodel += [M[1][9] == M[1][9] + 4]\nmodel += [M[2][1] == 3 * M[5][6]]\nmodel += [M[3][3] == M[2][2] / 16]\nmodel += [M[4][5] == M[6][7] * 15]\nmodel += [M[4][0] == M[3][2] - 399]\nmodel += [M[5][1] == M[7][1] / 18]\nmodel += [M[5][2] == M[5][7] - 94]\nmodel += [M[5][3] == M[5][3] - 9]\nmodel += [M[5][4] == M[6][0] - 52]\nmodel += [M[5][7] == M[5][7] * 6]\nmodel += [M[6][5] == 5 * M[5][6]]\nmodel += [M[6][7] == M[5][4] + 27]\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = [[int(x.value()) if x.value() is not None else 0 for x in row] for row in M]\n print(json.dumps({\"M\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_024_langford", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 4 # Numbers from 1 to n\nk = 4 # Number of sets\n\n# Model\nmodel = Model()\n\n# Variables\nposition = [[intvar(1, n*k, name=f\"pos_{i}_{j}\") for j in range(n)] for i in range(k)]\nsolution = intvar(1, n*k, shape=(n*k,), name=\"solution\")\n\n# Constraints\nfor i in range(k):\n for j in range(n):\n model += [position[i][j] <= n*k]\n\nfor i in range(k):\n for j in range(n):\n model += [position[i][j] != position[i][(j+1)%n]]\n\nfor m in range(1, n+1):\n for i in range(k-1):\n model += [position[i][m-1] + m + 1 == position[i+1][m-1]]\n\nfor p in range(n*k):\n model += [sum([solution[p] == m for m in range(1, n+1)]) == 1]\n\nfor i in range(k):\n for j in range(n):\n model += [solution[position[i][j]-1] == j+1]\n\n# Solve\nif model.solve():\n # Extract positions and solution\n pos_sol = [[position[i][j].value() for j in range(n)] for i in range(k)]\n sol = [solution[i].value() for i in range(n*k)]\n\n # Print as JSON\n output = {\n \"position\": pos_sol,\n \"solution\": sol\n }\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_026_sports_tournament_scheduling", "model": "from cpmpy import *\nimport json\n\nn_teams = 8\n\n# Create the model\nm = Model()\n\n# Create variables for the home and away schedules\nhome = [[m.var(type=\"int\", name=f\"home_{week}_{period}\") for period in range(n_teams//2)] for week in range(n_teams-1)]\naway = [[m.var(type=\"int\", name=f\"away_{week}_{period}\") for period in range(n_teams//2)] for week in range(n_teams-1)]\n\n# Constraints: every team plays once a week\nfor week in range(n_teams-1):\n for team in range(n_teams):\n m += sum([home[week][period] == team for period in range(n_teams//2)] + [away[week][period] == team for period in range(n_teams//2)]) == 1\n\n# Constraints: every team plays at most twice in the same period over the tournament\nfor period in range(n_teams//2):\n for team in range(n_teams):\n m += sum([home[week][period] == team for week in range(n_teams-1)] + [away[week][period] == team for week in range(n_teams-1)]) <= 2\n\n# Constraints: every team plays every other team\nfor team1 in range(n_teams):\n for team2 in range(team1+1, n_teams):\n m += sum([home[week][period] == team1 and away[week][period] == team2 for week in range(n_teams-1) for period in range(n_teams//2)]) == 1\n m += sum([home[week][period] == team2 and away[week][period] == team1 for week in range(n_teams-1) for period in range(n_teams//2)]) == 1\n\n# Solve the model\nif m.solve():\n # Extract the solution\n home_schedule = [[home[week][period].value() for period in range(n_teams//2)] for week in range(n_teams-1)]\n away_schedule = [[away[week][period].value() for period in range(n_teams//2)] for week in range(n_teams-1)]\n\n # Print the solution as a JSON object\n print(json.dumps({\"home\": home_schedule, \"away\": away_schedule}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_028_bibd", "model": "from cpmpy import *\nimport numpy as np\nimport json\n\n# 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\n# Variables\nx = boolvar((v, b), name=\"x\")\n\n# Constraints\nmodel = Model(\n [sum(x[i, :]) == r for i in range(v)], # Each object occurs in exactly r blocks\n [sum(x[:, j]) == k for j in range(b)], # Each block contains exactly k objects\n [sum([x[i1, j] * x[i2, j] for j in range(b)]) == l for i1 in range(v) for i2 in range(i1 + 1, v)] # Each pair of objects occurs together in exactly l blocks\n)\n\n# Solve\nif model.solve():\n # Get the solution\n solution = x.value()\n\n # Convert the solution to a JSON object\n json_solution = {\n \"matrix\": solution.tolist()\n }\n\n # Print the JSON object\n print(json.dumps(json_solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_033_word_design", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 8\nalphabet = ['A', 'C', 'G', 'T']\n\n# Model\nmodel = Model()\n\n# Variables\nwords = []\nfor i in range(n):\n word = [model.var(type='string', value_one_of=alphabet) for _ in range(8)]\n words.append(word)\n\n# Constraints\nfor word in words:\n # Each word has 4 symbols from {C, G}\n model += sum([word[i] == 'C' or word[i] == 'G' for i in range(8)]) == 4\n\nfor i in range(n):\n for j in range(i+1, n):\n # Each pair of distinct words differ in at least 4 positions\n model += sum([words[i][k] != words[j][k] for k in range(8)]) >= 4\n\nfor i in range(n):\n for j in range(n):\n # Each pair of words x and y (where x and y may be identical) are such that x^R and y^C differ in at least 4 positions\n x_R = [words[i][7-k] for k in range(8)]\n y_C = []\n for k in range(8):\n if words[j][k] == 'A':\n y_C.append('T')\n elif words[j][k] == 'T':\n y_C.append('A')\n elif words[j][k] == 'C':\n y_C.append('G')\n elif words[j][k] == 'G':\n y_C.append('C')\n model += sum([x_R[k] != y_C[k] for k in range(8)]) >= 4\n\n# Solve\nif model.solve():\n # Get the solution\n solution = []\n for word in words:\n solution.append(''.join([word[i].value() for i in range(8)]))\n\n # Print the solution as a JSON object\n print(json.dumps({'words': solution}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_044_steiner", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 9\n\n# Model\nsets = []\nfor i in range(n*(n-1)//6):\n sets.append([BooleanVariable() for _ in range(n)])\n\nmodel = Model(\n # Each element is in (n-1)/2 sets\n [sum([sets[j][i] for j in range(n*(n-1)//6)]) == (n-1)//2 for i in range(n)],\n\n # Each set contains exactly 3 elements\n [sum(sets[j]) == 3 for j in range(n*(n-1)//6)],\n\n # Any two sets have at most one common element\n [sum([sets[j][i]*sets[k][i] for i in range(n)]) <= 1 \n for j in range(n*(n-1)//6) for k in range(j+1, n*(n-1)//6)]\n)\n\n# Solve\nif model.solve():\n # Extract solution\n solution_sets = []\n for j in range(n*(n-1)//6):\n solution_set = [i+1 for i in range(n) if sets[j][i].value()]\n solution_sets.append(solution_set)\n\n # Print solution as JSON\n print(json.dumps({\"sets\": solution_sets}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_049_number_partitioning", "model": "from cpmpy import *\nimport json\n\nn = 12\n\n# Model\nx = boolvar(shape=n, name=\"x\")\n\nmodel = Model(\n [Sum(x) == n // 2], # Same cardinality\n [Sum([i + 1 for i in range(n) if x[i]]) == Sum([i + 1 for i in range(n) if not x[i]])], # Sum of numbers\n [Sum([(i + 1) ** 2 for i in range(n) if x[i]]) == Sum([(i + 1) ** 2 for i in range(n) if not x[i]])] # Sum of squares\n)\n\n# Solve\nif model.solve():\n A = [i + 1 for i in range(n) if x[i].value()]\n B = [i + 1 for i in range(n) if not x[i].value()]\n print(json.dumps({\"A\": A, \"B\": B}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_050_diamond_free", "model": "from cpmpy import *\nimport numpy as np\nimport json\n\nN = 10\n\n# Create model\nmodel = Model()\n\n# Create variables\nmatrix = boolvar(shape=(N, N), name=\"matrix\")\n\n# Create constraints\nfor i in range(N):\n for j in range(i+1, N):\n model += [matrix[i, j] == matrix[j, i]] # Symmetry constraint\n\nfor i in range(N):\n model += [sum([matrix[i, j] for j in range(N)]) % 3 == 0] # Degree is modulo 3\n model += [sum([matrix[i, j] for j in range(N)]) > 0] # Degree is greater than 0\n\nmodel += [sum([sum(row) for row in matrix]) % 12 == 0] # Sum of degrees is modulo 12\n\nfor i in range(N):\n for j in range(i+1, N):\n for k in range(j+1, N):\n for l in range(k+1, N):\n model += [matrix[i, j] + matrix[i, k] + matrix[i, l] + matrix[j, k] + matrix[j, l] + matrix[k, l] <= 4] # Diamond-free constraint\n\n# Solve model\nif model.solve():\n # Print solution\n solution_matrix = matrix.value()\n print(json.dumps({\"matrix\": solution_matrix.tolist()}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_053_graceful_graphs", "model": "from cpmpy import *\nimport json\n\n# 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\n# Model\nmodel = Model()\n\n# Node labels\nnode_labels = intvar(0, m, shape=n, name=\"node_labels\")\n\n# Edge labels\nedge_labels = intvar(1, m, shape=m, name=\"edge_labels\")\n\n# Constraints\nfor i in range(n):\n model += [node_labels[i] <= m]\n\nmodel += [AllDifferent(node_labels)]\nmodel += [AllDifferent(edge_labels)]\n\nfor i, edge in enumerate(graph):\n model += [edge_labels[i] == abs(node_labels[edge[0]] - node_labels[edge[1]])]\n\n# Solve\nif model.solve():\n # Output solution as JSON\n solution = {\n \"nodes\": [node_labels[i].value() for i in range(n)],\n \"edges\": [edge_labels[i].value() for i in range(m)]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_054_n_queens", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 10\n\n# Variables\nqueens = [intvar(1, n, name=f\"q{i}\") for i in range(n)]\n\n# Constraints\nmodel = Model(\n # All queens are in different rows\n [AllDifferent(queens)],\n # No two queens are on the same diagonal\n [AllDifferent([queens[i] - i - 1 for i in range(n)])],\n [AllDifferent([queens[i] + i + 1 for i in range(n)])]\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\n \"queens\": [q.value() for q in queens]\n }\n print(json.dumps(solution, indent=4))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_076_costas_arrays", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 8\n\n# Model\nx = intvar(1, n, shape=n, name=\"x\")\n\n# Constraints\nmodel = Model(\n AllDifferent(x),\n [AllDifferent([x[i] - x[i+l] for i in range(n-l)]) for l in range(1, n)]\n)\n\n# Solve\nif model.solve():\n costas = [x[i].value() for i in range(n)]\n print(json.dumps({\"costas\": costas}))\nelse:\n print(\"No solution found\")"} +{"id": "csplib__csplib_084_hadamard_matrix", "model": "from cpmpy import *\nimport json\n\n# Input data\nl = 9 # Value of l (must be an odd positive integer)\nm = (l - 1) // 2\n\n# Model\na = intvar(-1, 1, shape=l, name=\"a\")\nb = intvar(-1, 1, shape=l, name=\"b\")\n\nmodel = Model(\n [sum([a[i] * a[(i + s) % l] for i in range(l)]) + sum([b[i] * b[(i + s) % l] for i in range(l)]) == -2 for s in range(1, m + 1)],\n [sum(a) == 1],\n [sum(b) == 1]\n)\n\n# Solve\nif model.solve():\n solution = {\n \"a\": [a[i].value() for i in range(l)],\n \"b\": [b[i].value() for i in range(l)]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__abbots_puzzle", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nmen = intvar(0, 100, name=\"men\")\nwomen = intvar(0, 100, name=\"women\")\nchildren = intvar(0, 100, name=\"children\")\n\n# Define the constraints\nmodel += [men + women + children == 100, # total number of people\n 3 * men + 2 * women + 0.5 * children == 100, # total bushels of corn\n women == 5 * men] # five times as many women as men\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"men\": men.value(), \"women\": women.value(), \"children\": children.value()}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__added_corners", "model": "from cpmpy import *\nimport json\n\n# Define the model\nm = Model()\n\n# Define the variables\npositions = intvar(1, 8, shape=8, name=\"positions\")\n\n# Define the constraints\nm += AllDifferent(positions)\n\n# Define the constraints for each square\nm += (positions[0] + positions[1] == positions[2])\nm += (positions[2] + positions[3] == positions[4])\nm += (positions[4] + positions[5] == positions[6])\nm += (positions[6] + positions[7] == positions[0])\n\n# Solve the model\nif m.solve():\n # Print the solution as a JSON object\n solution = {\"positions\": list(positions.value)}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__ages_of_the_sons", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nA1, A2, A3 = intvar(1, 36), intvar(1, 36), intvar(1, 36)\n\n# Define the model\nmodel = Model(\n [A1 * A2 * A3 == 36], # Product of ages is 36\n [A1 + A2 + A3 > 10], # Sum of ages must be greater than 10 (minimum number of windows)\n [A1 + A2 + A3 < 37], # Sum of ages must be less than 37 (maximum number of windows)\n [A1 >= A2, A1 >= A3], # A1 is the oldest son\n [A2 != A3] # A2 and A3 must be different to satisfy the condition that the mathematician needed more information\n)\n\n# Solve the model\nif model.solve():\n # Get the solution\n solution = {\n \"A3\": int(max(A1.value(), A2.value(), A3.value())),\n \"A1\": int(sorted([A1.value(), A2.value(), A3.value()])[1]),\n \"A2\": int(min(A1.value(), A2.value(), A3.value()))\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found.\")"} +{"id": "hakan_examples__age_changing", "model": "from cpmpy import *\nimport json\nimport itertools\n\n# Define the operations\noperations = [\"+2\", \"/8\", \"-3\", \"*7\"]\n\n# Generate all permutations of operations\nperms = list(itertools.permutations(operations))\n\n# Define the model\nm = int_var(1, 100, name=\"m\") # my age\nh = int_var(1, 100, name=\"h\") # husband's age\n\n# Apply the operations\ndef apply_operations(age, ops):\n result = age\n for op in ops:\n if op == \"+2\":\n result += 2\n elif op == \"/8\":\n result = result // 8\n elif op == \"-3\":\n result -= 3\n elif op == \"*7\":\n result *= 7\n return result\n\n# Constraints\nmodel = Model()\nfor p1 in perms:\n for p2 in perms:\n if p1 != p2:\n model += apply_operations(m, p1) == h\n model += apply_operations(h, p2) == m\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"m\": m.value(), \"h\": h.value()}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__allergy", "model": "from cpmpy import *\nimport json\n\n# Define the friends and surnames\nfriends = [0, 1, 2, 3] # Debra = 0, Janet = 1, Hugh = 2, Rick = 3\nsurnames = [\"malone\", \"baxter\", \"fleet\", \"lemon\"]\nallergies = [\"eggs\", \"mold\", \"nuts\", \"ragweed\"]\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nsurname_vars = boolvar(shape=(4, 4), name=\"surname\")\nallergy_vars = boolvar(shape=(4, 4), name=\"allergy\")\n\n# Each friend has exactly one surname\nfor f in friends:\n model += sum(surname_vars[f, :]) == 1\n\n# Each surname is assigned to exactly one friend\nfor s in range(4):\n model += sum(surname_vars[:, s]) == 1\n\n# Each friend has exactly one allergy\nfor f in friends:\n model += sum(allergy_vars[f, :]) == 1\n\n# Each allergy is assigned to exactly one friend\nfor a in range(4):\n model += sum(allergy_vars[:, a]) == 1\n\n# Rick is not allergic to mold\nmodel += ~allergy_vars[3, 1]\n\n# Baxter is allergic to eggs\nmodel += surname_vars[:, 1] == allergy_vars[:, 0]\n\n# Hugh is neither surnamed Lemon nor Fleet\nmodel += ~(surname_vars[2, 3] | surname_vars[2, 2])\n\n# Debra is allergic to ragweed\nmodel += allergy_vars[0, 3]\n\n# Janet (who isn't Lemon) is neither allergic to eggs nor to mold\nmodel += ~(surname_vars[1, 3] | allergy_vars[1, 0] | allergy_vars[1, 1])\n\n# Solve the model\nif model.solve():\n # Extract the solution\n solution = {}\n for f in friends:\n for s in range(4):\n if model[surname_vars[f, s]]:\n solution[surnames[s]] = f\n for a in range(4):\n if model[allergy_vars[f, a]]:\n solution[allergies[a]] = f\n\n # Print the solution as a JSON object\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__among", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 5\nm = 3\nv = [1, 5, 8]\n\n# Model\nx = intvar(lb=min(v), ub=max(v), shape=n, name=\"x\")\n\nmodel = Model(\n [x[i] in v for i in range(n)],\n [Sum([x[i] == val for i in range(n) for val in v]) == m]\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n sol = {f\"x_{i}\": x[i].value() for i in range(n)}\n print(json.dumps(sol, indent=4))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__appointment_scheduling", "model": "from cpmpy import *\nimport json\n\n# Data\nm = [[1, 1, 1, 1], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1]]\n\n# Model\nx = boolvar(shape=(4, 4), name=\"x\")\n\nmodel = Model(\n [sum(x[i, :]) == 1 for i in range(4)], # Each person is assigned to exactly one slot\n [sum(x[:, j]) == 1 for j in range(4)], # Each slot is assigned to exactly one person\n [x[i, j] <= m[i][j] for i in range(4) for j in range(4)] # Person can only be assigned to free slots\n)\n\n# Solve\nif model.solve():\n # Extract solution\n x_val = x.value()\n solution = {\"x\": [[int(x_val[i][j]) for j in range(4)] for i in range(4)]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__archery_puzzle", "model": "from cpmpy import *\nimport json\n\n# Define the targets\ntargets = [16, 17, 23, 24, 39, 40]\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\nhits = [intvar(0, 100, name=f\"hits_{i}\") for i in range(len(targets))]\n\n# Define the objective: minimize the difference to 100\ndiff = intvar(0, 100, name=\"diff\")\nmodel += diff == abs(sum([hits[i] * targets[i] for i in range(len(targets))]) - 100)\n\n# Solve the model\nif model.solve():\n # Extract the solution\n solution = {f\"hits_{i}\": hits[i].value() for i in range(len(targets))}\n solution[\"hits\"] = solution\n del solution[\"hits_0\"]\n del solution[\"hits_1\"]\n del solution[\"hits_2\"]\n del solution[\"hits_3\"]\n del solution[\"hits_4\"]\n del solution[\"hits_5\"]\n for i in range(len(targets)):\n solution[f\"hits\"][f\"target_{targets[i]}\"] = solution[f\"hits_{i}\"]\n del solution[f\"hits_{i}\"]\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__arch_friends", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nshoes = [\"ecruespadrilles\", \"fuchsiaflats\", \"purplepumps\", \"suedesandals\"]\nstores = [\"footfarm\", \"heelsinahandcart\", \"theshoepalace\", \"tootsies\"]\n\n# Create the model\nmodel = Model()\n\n# Create the variables\nshoe_vars = [intvar(1, 4, name=shoe) for shoe in shoes]\nstore_vars = [intvar(1, 4, name=store) for store in stores]\n\n# Add constraints\nmodel += [AllDifferent(shoe_vars)]\nmodel += [AllDifferent(store_vars)]\n\n# Constraint 1: Fuchsia flats at Heels in a Handcart\nmodel += [store_vars[stores.index(\"heelsinahandcart\")] == shoe_vars[shoes.index(\"fuchsiaflats\")]]\n\n# Constraint 2: Store after purple pumps is not Tootsies\nmodel += [store_vars[stores.index(\"tootsies\")] != shoe_vars[shoes.index(\"purplepumps\")] + 1]\n\n# Constraint 3: Foot Farm is the second stop\nmodel += [store_vars[stores.index(\"footfarm\")] == 2]\n\n# Constraint 4: Two stops after The Shoe Palace, Harriet bought her suede sandals\nmodel += [store_vars[stores.index(\"theshoepalace\")] + 2 == shoe_vars[shoes.index(\"suedesandals\")]]\n\n# Solve the model\nif model.solve():\n # Get the solution\n solution = {\n \"ecruespadrilles\": shoe_vars[shoes.index(\"ecruespadrilles\")].value(),\n \"fuchsiaflats\": shoe_vars[shoes.index(\"fuchsiaflats\")].value(),\n \"purplepumps\": shoe_vars[shoes.index(\"purplepumps\")].value(),\n \"suedesandals\": shoe_vars[shoes.index(\"suedesandals\")].value(),\n \"footfarm\": store_vars[stores.index(\"footfarm\")].value(),\n \"heelsinahandcart\": store_vars[stores.index(\"heelsinahandcart\")].value(),\n \"theshoepalace\": store_vars[stores.index(\"theshoepalace\")].value(),\n \"tootsies\": store_vars[stores.index(\"tootsies\")].value()\n }\n\n # Print the solution as a JSON object\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__assignment_costs", "model": "from cpmpy import *\nimport json\nimport numpy as np\n\n# Data\ncost = np.array([\n [14, 5, 8, 7, 15],\n [2, 12, 6, 5, 3],\n [7, 8, 3, 9, 7],\n [2, 4, 6, 10, 1]\n])\n\n# Model\nmodel = Model()\n\n# Variables\nx = boolvar((4, 5), name=\"x\")\n\n# Constraints\nfor i in range(4):\n model += sum([x[i, j] for j in range(5)]) == 1 # Each task is assigned to exactly one person\n\nfor j in range(5):\n model += sum([x[i, j] for i in range(4)]) <= 1 # Each person can be assigned to at most one task\n\n# Objective\nmodel.minimize(sum([sum([cost[i, j] * x[i, j] for j in range(5)]) for i in range(4)]))\n\n# Solve\nif model.solve():\n # Get the solution\n x_sol = x.value()\n\n # Print the solution as a JSON object\n print(json.dumps({\"x\": x_sol.tolist()}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__autoref", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 27\nm = 5\n\n# Model\ns = intvar(0, n+1, shape=n+2, name=\"s\")\n\nmodel = Model(\n [sum(s) == sum(range(n+1)) + m], # sum of occurrences equals sum of numbers from 0 to n plus m\n [s[i] == i for i in range(n+1)], # si occurrences of i in S for each integer i ranging from 0 to n\n [s[n+1] == m] # sn+1 = m\n)\n\n# Solve\nif model.solve():\n solution = {\"s\": list(s.value())}\n print(json.dumps(solution))\nelse:\n print(\"No solution found.\")"} +{"id": "hakan_examples__bales_of_hay", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nbales = intvar(0, 100, shape=5, name=\"bales\")\n\n# Define the constraints\ncombinations = []\nfor i in range(5):\n for j in range(i+1, 5):\n combinations.append(bales[i] + bales[j])\n\nmodel += AllDifferent(combinations)\nmodel += [combinations[i] == [80, 82, 83, 84, 85, 86, 87, 88, 90, 91][i] for i in range(10)]\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"bales\": [int(b) for b in bales.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__bananas", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nbananas = intvar(0, 100, name=\"bananas\")\noranges = intvar(0, 100, name=\"oranges\")\nmangoes = intvar(0, 100, name=\"mangoes\")\napples = intvar(0, 100, name=\"apples\")\n\n# Define the constraints\nmodel += (5 * bananas + 7 * oranges + 9 * mangoes + 3 * apples == 100) # total fruits constraint\nmodel += (3 * bananas + 5 * oranges + 7 * mangoes + 9 * apples == 100) # total cost constraint\nmodel += (bananas >= 0) # non-negativity constraint for bananas\nmodel += (oranges >= 0) # non-negativity constraint for oranges\nmodel += (mangoes >= 0) # non-negativity constraint for mangoes\nmodel += (apples >= 0) # non-negativity constraint for apples\nmodel += (bananas >= 5 * (bananas > 0)) # buying constraint for bananas\nmodel += (oranges >= 7 * (oranges > 0)) # buying constraint for oranges\nmodel += (mangoes >= 9 * (mangoes > 0)) # buying constraint for mangoes\nmodel += (apples >= 3 * (apples > 0)) # buying constraint for apples\n\n# Minimize the quantity of bananas and apples\nmodel.minimize(bananas + apples)\n\n# Solve the model\nstatus = model.solve()\n\n# Print the solution as a JSON object\nif status:\n solution = {\n \"bananas\": bananas.value(),\n \"oranges\": oranges.value(),\n \"apples\": apples.value(),\n \"mangoes\": mangoes.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__best_host", "model": "from cpmpy import *\nimport json\n\n# Define the guests\nguests = [\"Andrew\", \"Betty\", \"Cara\", \"Dave\", \"Erica\", \"Frank\"]\n\n# Define the allowed neighbors for each guest\nneighbors = {\n \"Andrew\": [\"Dave\", \"Frank\"],\n \"Betty\": [\"Cara\", \"Erica\"],\n \"Cara\": [\"Betty\", \"Frank\"],\n \"Dave\": [\"Andrew\", \"Erica\"],\n \"Erica\": [\"Betty\", \"Dave\"],\n \"Frank\": [\"Andrew\", \"Cara\"]\n}\n\n# Create the model\nmodel = Model()\n\n# Create the variables\nx = intvar(0, 5, shape=6, name=\"x\")\n\n# Create the constraints\nfor i in range(6):\n for j in range(i+1, 6):\n if i == j-1:\n model += (Element([guests.index(n) for n in neighbors[guests[x[i]]]], x[j]) == 1)\n elif i == j+1:\n model += (Element([guests.index(n) for n in neighbors[guests[x[j]]]], x[i]) == 1)\n\n# Add constraint to ensure all guests are seated\nmodel += AllDifferent(x)\n\n# Solve the model\nif model.solve():\n # Print the solution\n solution = [guests[i] for i in x.value()]\n print(json.dumps({\"x\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__big_bang2", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\ndice = [[model.int_var(1, 6) for _ in range(6)] for _ in range(5)]\n\n# Define the constraints\nfor i in range(5):\n model.add_all_different(dice[i])\n\n# Define the dominance relationships\ndominance = {\n (0, 2), (0, 3), # Rock(1) crushes Scissors(3), Rock(1) crushes Lizard(4)\n (1, 0), (1, 4), # Paper(2) covers Rock(1), Paper(2) disproves Spock(5)\n (2, 1), (2, 3), # Scissors(3) cuts Paper(2), Scissors(3) decapitate Lizard(4)\n (3, 1), (3, 4), # Lizard(4) eats Paper(2), Lizard(4) poisons Spock(5)\n (4, 0), (4, 2) # Spock(5) vaporizes Rock(1), Spock(5) smashes Scissors(3)\n}\n\n# Add the dominance constraints\nfor i, j in dominance:\n for k in range(6):\n for l in range(6):\n model.add(dice[i][k] > dice[j][l])\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"dice\": [[int(x.value()) for x in die] for die in dice]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__bin_packing", "model": "from cpmpy import *\nimport json\n\n# Data\nweights = [4, 3, 1, 3, 2, 5, 2]\ncapacity = 5\nnum_bins = 5\nnum_items = len(weights)\n\n# Model\nmodel = Model()\n\n# Variables\nbins = intvar(1, num_bins, shape=num_items, name=\"bins\")\n\n# Constraints\nfor b in range(1, num_bins + 1):\n model += sum([weights[i] for i in range(num_items) if bins[i] == b]) <= capacity\n\n# Solve\nif model.solve():\n # Output solution\n output = {\"bins\": [bins[i].value() for i in range(num_items)]}\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__birthday_coins", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nhalf_crowns = intvar(0, 15, name=\"half_crowns\")\nshillings = intvar(0, 15, name=\"shillings\")\nsixpence = intvar(0, 15, name=\"sixpence\")\n\n# Define the model\nmodel = Model(\n [half_crowns + shillings + sixpence == 15, # Total number of coins\n 30 * half_crowns + 12 * shillings + 6 * sixpence == 246] # Total value in pence\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"half_crowns\": half_crowns.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__bowls_and_oranges", "model": "from cpmpy import *\nimport json\n\n# Model\nn_bowls = 40\nn_oranges = 9\n\nx = intvar(1, n_bowls, shape=n_oranges, name=\"x\")\n\nmodel = Model(\n [AllDifferent(x)], # all oranges in different bowls\n [x[i] < x[j] for i in range(n_oranges) for j in range(i+1, n_oranges) if abs(i-j) == 2] # no three oranges with equal distances\n)\n\n# Solve\nif model.solve():\n solution = {f\"x_{i+1}\": x[i].value() for i in range(n_oranges)}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__broken_weights", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nweights = intvar(1, 40, shape=4, name=\"weights\")\n\n# Define the model\nmodel = Model(\n # The sum of the weights should be 40\n sum(weights) == 40,\n # All weights should be different\n AllDifferent(weights)\n)\n\n# Define the constraints for weighing all integral weights between 1 and 40 pounds\nfor i in range(1, 41):\n model += (sum([w * (1 if j < 2**k else -1) for k, (w, j) in enumerate(zip(weights, range(4)))]) == i for j in range(2**4) if sum([1 if j & (1 << k) else 0 for k in range(4)]) <= 3)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n print(json.dumps({\"weights\": [w.value() for w in weights]}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__building_blocks", "model": "from cpmpy import *\nimport json\n\n# Define the letters\nletters = [c for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if c not in 'QZ']\n\n# Define the words\nwords = ['BAKE', 'ONYX', 'ECHO', 'OVAL', 'GIRD', 'SMUG', 'JUMP', 'TORN', 'LUCK', 'VINY', 'LUSH', 'WRAP']\n\n# Create the model\nmodel = Model()\n\n# Decision variable: which block each letter is on\ndice = {letter: int_var(0, 3, name=letter) for letter in letters}\n\n# Each block contains exactly 6 letters\nfor block in range(4):\n model += sum([dice[letter] == block for letter in letters]) == 6\n\n# Each letter is on exactly one block\nfor letter in letters:\n model += sum([dice[letter] == block for block in range(4)]) == 1\n\n# For each word, all letters must be on different blocks\nfor word in words:\n model += AllDifferent([dice[letter] for letter in word])\n\n# Solve the model\nif model.solve():\n # Create the output dictionary\n output = {\n 'dice': [dice[letter].value() for letter in letters]\n }\n\n # Print the output as JSON\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__cabling", "model": "from cpmpy import *\nimport json\n\n# Define the devices\ndevices = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"]\n\n# Define the connections\nconnections = {\n (\"A\", \"H\"): 1,\n (\"A\", \"E\"): 2,\n (\"B\", \"F\"): 4,\n (\"C\", \"G\"): 1,\n (\"C\", \"D\"): 1,\n (\"C\", \"E\"): 1,\n (\"D\", \"H\"): 3,\n (\"G\", \"H\"): 1,\n}\n\n# Define the model\nmodel = Model()\n\n# Define the variables\ndevice_order = intvar(0, 7, shape=len(devices), name=\"device_order\")\n\n# Define the constraints\nfor i in range(len(devices)):\n model += [device_order[i] >= 0, device_order[i] < len(devices)]\nmodel += [AllDifferent(device_order)]\n\n# Define the objective function\ndef calculate_cable_length(device_order):\n cable_length = 0\n for connection, num_cables in connections.items():\n device1_index = devices.index(connection[0])\n device2_index = devices.index(connection[1])\n device1_position = device_order[device1_index]\n device2_position = device_order[device2_index]\n cable_length += num_cables * abs(device1_position - device2_position)\n return cable_length\n\n# Solve the model\nif model.solve():\n # Calculate the final sum of all cable lengths\n final_sum = calculate_cable_length([device_order[i].value() for i in range(len(devices))])\n\n # Print the solution as a JSON object\n solution = {\"final_sum\": final_sum}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__calvin_puzzle", "model": "from cpmpy import *\nimport numpy as np\nimport json\n\nn = 5\n\n# Create a 2D grid of variables\nx = intvar(1, n*n, shape=(n, n), name=\"x\")\n\n# Create a model\nmodel = Model()\n\n# Constraints: each number appears exactly once\nfor i in range(1, n*n+1):\n model += sum([x[j, k] == i for j in range(n) for k in range(n)]) == 1\n\n# Constraints: Movement Type I and II\nfor i in range(1, n*n):\n prev_var = intvar(1, n*n, name=f\"prev_{i}\")\n next_var = intvar(1, n*n, name=f\"next_{i}\")\n model += prev_var == i\n model += next_var == i + 1\n\n # Horizontal movement\n for j in range(n):\n for k in range(n-3):\n model += (x[j, k] == prev_var) & (x[j, k+3] == next_var) | (x[j, k] == next_var) & (x[j, k+3] == prev_var)\n\n # Vertical movement\n for j in range(n-3):\n for k in range(n):\n model += (x[j, k] == prev_var) & (x[j+3, k] == next_var) | (x[j, k] == next_var) & (x[j+3, k] == prev_var)\n\n # Diagonal movement (top-left to bottom-right)\n for j in range(n-2):\n for k in range(n-2):\n model += (x[j, k] == prev_var) & (x[j+2, k+2] == next_var) | (x[j, k] == next_var) & (x[j+2, k+2] == prev_var)\n\n # Diagonal movement (bottom-left to top-right)\n for j in range(2, n):\n for k in range(n-2):\n model += (x[j, k] == prev_var) & (x[j-2, k+2] == next_var) | (x[j, k] == next_var) & (x[j-2, k+2] == prev_var)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = x.value()\n print(json.dumps({\"x\": solution.tolist()}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__candies", "model": "from cpmpy import *\nimport json\n\n# Data\nratings = [2, 3, 4, 4, 4, 2, 1, 3, 4]\nn = len(ratings)\n\n# Model\nmodel = Model()\nx = [model.intvar(1, n, \"x{}\".format(i)) for i in range(n)]\nz = model.intvar(0, n*n, \"z\")\n\n# Constraints\nfor i in range(n):\n if i > 0 and ratings[i] > ratings[i-1]:\n model += x[i] > x[i-1]\n if i < n-1 and ratings[i] > ratings[i+1]:\n model += x[i] > x[i+1]\n\nmodel += z == sum(x)\n\n# Solve\nif model.solve():\n print(json.dumps({\"z\": z.value()}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__capital_budget", "model": "from cpmpy import *\nimport json\n\n# Define the NPV and costs of the investments\nnpv = [16000, 22000, 12000, 8000]\ncosts = [5000, 7000, 4000, 3000]\n\n# Define the available budget\nbudget = 14000\n\n# Define the decision variables\nx = boolvar(shape=len(npv), name=\"x\")\n\n# Define the model\nmodel = Model(\n maximize=sum([npv[i] * x[i] for i in range(len(npv))]),\n [sum([costs[i] * x[i] for i in range(len(costs))]) <= budget]\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = { \"x\": [x[i].value() for i in range(len(x))] }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__chess_set", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nsmall_set = intvar(0, 200, name=\"small_set\")\nlarge_set = intvar(0, 200, name=\"large_set\")\n\n# Define the constraints\nconstraints = [\n 3 * small_set + 2 * large_set <= 160, # Lathe-hours constraint\n small_set + 3 * large_set <= 200 # Boxwood constraint\n]\n\n# Define the objective function\nobj = 5 * small_set + 20 * large_set\n\n# Create the model\nmodel = Model(constraints=constraints, objective=obj, minimize=False)\n\n# Solve the model\nif model.solve():\n # Get the solution values\n small_set_value = small_set.value()\n large_set_value = large_set.value()\n max_profit = obj.value()\n\n # Print the solution as a JSON object\n print(json.dumps({\n \"small_set\": small_set_value,\n \"large_set\": large_set_value,\n \"max_profit\": max_profit\n }))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__circling_squares", "model": "from cpmpy import *\nimport json\n\n# Define the model\nm = Model()\n\n# Define the variables\nA, B, C, D, E, F, G, H, I, K = [int_var(1, 20) for _ in range(10)]\n\n# Given values\nA.value = 16\nB.value = 2\nF.value = 8\nG.value = 14\n\n# Constraints\nm += [A**2 + K**2 == F**2 + E**2,\n B**2 + C**2 == G**2 + H**2,\n C**2 + D**2 == H**2 + I**2,\n D**2 + E**2 == I**2 + K**2,\n A**2 + B**2 == F**2 + G**2,\n G**2 + H**2 == B**2 + C**2,\n F**2 + E**2 == A**2 + K**2,\n H**2 + I**2 == C**2 + D**2,\n I**2 + K**2 == D**2 + E**2,\n AllDifferent([A, B, C, D, E, F, G, H, I, K])]\n\n# Solve the model\nif m.solve():\n # Create a dictionary with the solution\n solution = {\"A\": A.value(), \"B\": B.value(), \"C\": C.value(), \"D\": D.value(),\n \"E\": E.value(), \"F\": F.value(), \"G\": G.value(), \"H\": H.value(),\n \"I\": I.value(), \"K\": K.value()}\n \n # Print the solution as a JSON object\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__circular_table_averbach_1_2", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nx, y, z = intvar(0, 2, shape=3, name=\"x\")\namerican, english, french = intvar(0, 2, shape=3, name=\"nationality\")\n\n# Define the model\nmodel = Model(\n # Each person has a unique nationality\n AllDifferent([x, y, z]),\n AllDifferent([american, english, french]),\n # Y passed three hearts to the American\n y != american,\n # X passed the queen of spades and two diamonds to the person who passed their cards to the Frenchwoman\n x != z,\n (x + 1) % 3 == z, # X passed to Z\n (z + 1) % 3 == french, # Z is not the Frenchwoman, but the person who passed to the Frenchwoman\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"y\": y.value(),\n \"english\": english.value(),\n \"american\": american.value(),\n \"french\": french.value(),\n \"x\": x.value(),\n \"z\": z.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__clock_triplets", "model": "from cpmpy import *\nimport json\n\n# Model\nx = intvar(1, 12, shape=12, name=\"x\")\n\n# Constraints\nmodel = Model(\n AllDifferent(x),\n [x[0] == 12], # first number is 12\n [x[i] in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] for i in range(12)], # domain\n [x[11] == x[0]], # circular constraint\n [(x[i] + x[i+1] + x[(i+2)%12]) <= 21 for i in range(12)] # sum constraint\n)\n\n# Solve\nif model.solve():\n # Print solution\n solution = {\"x\": [x[i].value() for i in range(12)]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__cmo_2012", "model": "from cpmpy import *\nimport math\nimport json\n\ndef is_prime(num):\n if num < 2:\n return False\n for i in range(2, int(math.sqrt(num)) + 1):\n if num % i == 0:\n return False\n return True\n\ndef is_perfect_square(num):\n sqrt = math.sqrt(num)\n return sqrt == int(sqrt)\n\ndef model(a_min):\n a = intvar(a_min, 10000, name=\"a\")\n b = intvar(1, 10000, name=\"b\")\n n = intvar(1, 100, name=\"n\")\n p = intvar(2, 10000, name=\"p\")\n\n model = Model(\n [a - b == p, \n a * b == n * n, \n p > 1,\n [is_prime(p_) for p_ in range(p.value(), p.ub+1)],\n [is_perfect_square(n_ * n_) for n_ in range(n.value(), n.ub+1)]]\n )\n\n if model.solve():\n solution = {\n \"b\": b.value(),\n \"p\": p.value(),\n \"a\": a.value(),\n \"n\": n.value()\n }\n print(json.dumps(solution))\n else:\n print(\"No solution found\")\n\nmodel(2012)"} +{"id": "hakan_examples__coin3_application", "model": "from cpmpy import *\nimport json\n\n# Define the coin denominations\ndenominations = [1, 2, 5, 10, 20, 50]\n\n# Define the maximum amount to pay\nmax_amount = 100\n\n# Define the number of coins for each denomination\nx = intvar(0, max_amount, shape=len(denominations), name=\"x\")\n\n# Model\nmodel = Model(\n # Minimize the total number of coins\n minimize=sum(x)\n)\n\n# Constraints\nfor amount in range(1, max_amount):\n model += sum([x[i] * denominations[i] for i in range(len(denominations))]) >= amount\n\n# Solve the model\nif model.solve():\n # Extract the solution\n solution = [x[i].value() for i in range(len(denominations))]\n\n # Print the solution as a JSON object\n print(json.dumps({\"x\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__coins_grid", "model": "from cpmpy import *\nimport json\n\n# Define the size of the grid\nn = 31\n\n# Define the number of coins per row and column\nnum_coins = 14\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\nx = boolvar((n, n), name=\"x\")\n\n# Define the constraints\nfor i in range(n):\n model += sum([x[i, j] for j in range(n)]) == num_coins\n model += sum([x[j, i] for j in range(n)]) == num_coins\n\n# Define the objective function\nz = intvar(0, 1000000, name=\"z\")\nmodel += z == sum([x[i, j] * (i - j) ** 2 for i in range(n) for j in range(n)])\n\n# Solve the model\nif model.solve():\n # Extract the solution\n x_sol = [[int(x[i, j].value()) for j in range(n)] for i in range(n)]\n z_sol = int(z.value())\n\n # Print the solution as a JSON object\n print(json.dumps({\"x\": x_sol, \"z\": z_sol}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__contracting_costs", "model": "from cpmpy import *\nimport json\n\n# Define the model\nmodel = Model()\n\n# Define the variables\npaper_hanger = intvar(0, 10000, name=\"paper_hanger\")\npainter = intvar(0, 10000, name=\"painter\")\nplumber = intvar(0, 10000, name=\"plumber\")\nelectrician = intvar(0, 10000, name=\"electrician\")\ncarpenter = intvar(0, 10000, name=\"carpenter\")\nmason = intvar(0, 10000, name=\"mason\")\n\n# Define the constraints\nmodel += [paper_hanger + painter == 1100]\nmodel += [painter + plumber == 1700]\nmodel += [plumber + electrician == 1100]\nmodel += [electrician + carpenter == 3300]\nmodel += [carpenter + mason == 5300]\nmodel += [mason + painter == 3200]\n\n# Solve the model\nif model.solve():\n # Create a dictionary with the solution\n solution = {\n \"painter\": painter.value(),\n \"plumber\": plumber.value(),\n \"electrician\": electrician.value(),\n \"carpenter\": carpenter.value(),\n \"mason\": mason.value(),\n \"paper_hanger\": paper_hanger.value()\n }\n # Print the solution as a JSON object\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__covering_opl", "model": "import json\nfrom cpmpy import *\n\n# Data\nnb_workers = 32\nnum_tasks = 15\nQualified = [\n [1, 9, 19, 22, 25, 28, 31],\n [2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32],\n [3, 10, 19, 24, 26, 30, 32],\n [4, 21, 25, 28, 32],\n [5, 11, 16, 22, 23, 27, 31],\n [6, 20, 24, 26, 30, 32],\n [7, 12, 17, 25, 30, 31],\n [8, 17, 20, 22, 23],\n [9, 13, 14, 26, 29, 30, 31],\n [10, 21, 25, 31, 32],\n [14, 15, 18, 23, 24, 27, 30, 32],\n [18, 19, 22, 24, 26, 29, 31],\n [11, 20, 25, 28, 30, 32],\n [16, 19, 23, 31],\n [9, 18, 26, 28, 31, 32]\n]\nCost = [\n 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5,\n 5, 6, 6, 6, 7, 8, 9\n]\n\n# Model\nmodel = Model()\n\n# Decision variables\nworker = boolvar(shape=nb_workers, name=\"worker\")\n\n# Constraints\nfor i in range(num_tasks):\n model += sum([worker[j-1] for j in Qualified[i]]) >= 1\n\n# Objective function\nmodel.minimize(sum([Cost[i]*worker[i] for i in range(nb_workers)]))\n\n# Solve\nif model.solve():\n total_cost = model.objective_value()\n workers = [int(val) for val in model[worker].value()]\n output = {\n \"total_cost\": total_cost,\n \"workers\": workers\n }\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__crew", "model": "from cpmpy import *\nimport json\n\n# Data\nnum_attendants = 20\nnum_flights = 10\n\nattributes = [\n [1, 0, 0, 0, 1], # Tom\n [1, 0, 0, 0, 0], # David\n [1, 0, 0, 0, 1], # Jeremy\n [1, 0, 0, 0, 0], # Ron\n [1, 0, 0, 1, 0], # Joe\n [1, 0, 1, 1, 0], # Bill\n [1, 0, 0, 1, 0], # Fred\n [1, 0, 0, 0, 0], # Bob\n [1, 0, 0, 1, 1], # Mario\n [1, 0, 0, 0, 0], # Ed\n [0, 1, 0, 0, 0], # Carol\n [0, 1, 0, 0, 0], # Janet\n [0, 1, 0, 0, 0], # Tracy\n [0, 1, 0, 0, 0], # Marilyn\n [0, 1, 0, 0, 0], # Carolyn\n [0, 1, 0, 0, 0], # Cathy\n [0, 1, 1, 1, 1], # Inez\n [0, 1, 1, 0, 0], # Jean\n [0, 1, 0, 1, 1], # Heather\n [0, 1, 1, 0, 0] # Juliet\n]\n\nrequired_crew = [\n [4, 1, 1, 1, 1, 1], # Flight 1\n [5, 1, 1, 1, 1, 1], # Flight 2\n [5, 1, 1, 1, 1, 1], # Flight 3\n [6, 2, 2, 1, 1, 1], # Flight 4\n [7, 3, 3, 1, 1, 1], # Flight 5\n [4, 1, 1, 1, 1, 1], # Flight 6\n [5, 1, 1, 1, 1, 1], # Flight 7\n [6, 1, 1, 1, 1, 1], # Flight 8\n [6, 2, 2, 1, 1, 1], # Flight 9\n [7, 3, 3, 1, 1, 1] # Flight 10\n]\n\n# Model\nm = Model()\n\n# Decision variables\ncrew = [[m.Bool(f\"crew_{i}_{j}\") for j in range(num_flights)] for i in range(num_attendants)]\n\n# Constraints\nfor i in range(num_attendants):\n m += sum(crew[i]) <= 1 # Each attendant can be assigned to at most one flight\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants)) == required_crew[j][0] # Total crew constraint\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants) if attributes[i][0] == 1) == required_crew[j][1] # Steward constraint\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants) if attributes[i][1] == 1) == required_crew[j][2] # Hostess constraint\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants) if attributes[i][2] == 1) == required_crew[j][3] # French constraint\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants) if attributes[i][3] == 1) == required_crew[j][4] # Spanish constraint\n\nfor j in range(num_flights):\n m += sum(crew[i][j] for i in range(num_attendants) if attributes[i][4] == 1) == required_crew[j][5] # German constraint\n\n# Solve\nif m.solve():\n solution = [[int(crew[i][j].value()) for j in range(num_flights)] for i in range(num_attendants)]\n print(json.dumps({\"crew\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__crossword", "model": "from cpmpy import *\nimport json\n\n# Define the words\nwords = [\n \"AFT\",\n \"ALE\",\n \"EEL\",\n \"HEEL\",\n \"HIKE\",\n \"HOSES\",\n \"KEEL\",\n \"KNOT\",\n \"LASER\",\n \"LEE\",\n \"LINE\",\n \"SAILS\",\n \"SHEET\",\n \"STEER\",\n \"TIE\"\n]\n\n# Sort the words by length and then alphabetically\nwords.sort(key=lambda x: (-len(x), x))\n\n# Create a dictionary mapping words to indices\nword_indices = {word: i for i, word in enumerate(words)}\n\n# Define the crossword puzzle grid\ngrid = [\n [1, 1, None, 2, None, 3],\n [None, None, None, None, None, None],\n [None, 4, None, 5, None, None],\n [6, None, 7, None, None, None],\n [8, None, None, None, None, None],\n [None, None, None, None, None, None]\n]\n\n# Create the model\nmodel = Model()\n\n# Define the decision variables\nE = intvar(0, len(words) - 1, shape=8, name=\"E\")\n\n# Define the constraints\nfor i in range(6):\n for j in range(6):\n if grid[i][j] is not None:\n word_idx = grid[i][j] - 1\n word_len = len(words[E[word_idx]])\n if i + word_len <= 6:\n for k in range(word_len):\n model += (E[word_idx + k] == word_indices[words[E[word_idx]]])\n if j + word_len <= 6:\n for k in range(word_len):\n model += (E[word_idx + k] == word_indices[words[E[word_idx]]])\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"E\": [int(x) for x in E.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__crypta", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nA, B, C, D, E, F, G, H, I, J = intvar(0, 9, shape=10, name=\"vars\")\n\n# Define the model\nmodel = Model(\n AllDifferent([A, B, C, D, E, F, G, H, I, J]),\n [B + D == G + 10 * H],\n [A + H + 1 == E + 10 * J],\n [I + I + F + 1 == C + 10 * E],\n [J + B + G == D + 10 * C],\n [J + I + A == H + 10 * D],\n [A + F + 1 == F + 10 * J],\n [I + C == B + 10 * A],\n [B == G],\n [A != 0, D != 0, G != 0]\n)\n\n# Solve the model\nif model.solve():\n # Create a dictionary with the solution\n solution = {\n \"H\": H.value(),\n \"D\": D.value(),\n \"J\": J.value(),\n \"G\": G.value(),\n \"E\": E.value(),\n \"C\": C.value(),\n \"I\": I.value(),\n \"F\": F.value(),\n \"A\": A.value(),\n \"B\": B.value()\n }\n # Print the solution as JSON\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__eighteen_hole_golf", "model": "from cpmpy import *\nimport json\nimport random\n\n# Model\nholes = intvar(3, 5, shape=18, name=\"holes\")\n\n# Constraints\nmodel = Model(\n sum(holes) == 72,\n)\n\n# Solve\nif model.solve():\n # Get the solution\n solution = {f\"hole_{i+1}\": holes[i].value() for i in range(18)}\n print(json.dumps({\"holes\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__facility_location", "model": "from cpmpy import *\nimport json\n\n# Data\nwarehouse_s = [\"New York\", \"Los Angeles\", \"Chicago\", \"Atlanta\"]\nfixed_costs = [400, 500, 300, 150]\nmax_shipping = 100\ndemands = [80, 70, 40]\nshipping_costs = [\n [20, 40, 50],\n [48, 15, 26],\n [26, 35, 18],\n [24, 50, 35]\n]\n\n# Model\nm = Model()\n\n# Variables\nopen_warehouse = [m.Bool(f\"open_{w}\") for w in warehouse_s]\nships = [[m.Int(f\"ships_{w}_{r}\") for r in range(len(demands))] for w in warehouse_s]\n\n# Constraints\nfor w, (fixed_cost, warehouse) in enumerate(zip(fixed_costs, warehouse_s)):\n if warehouse == \"New York\":\n m += [open_warehouse[1] >= open_warehouse[0]] # If New York is open, Los Angeles must be open\n if warehouse == \"Atlanta\" or warehouse == \"Los Angeles\":\n m += [open_warehouse[w] + open_warehouse[1] + open_warehouse[2] >= 1] # Either Atlanta or Los Angeles must be open\n for r in range(len(demands)):\n m += [ships[w][r] <= max_shipping * open_warehouse[w]] # Shipping constraint\n m += [ships[w][r] >= 0]\n m += [sum(open_warehouse) <= 3] # No more than three warehouses can be open\n\n# Objective\ntotal_cost = m.Sum([fixed_costs[w] * open_warehouse[w] for w in range(len(warehouse_s))]) + m.Sum([shipping_costs[w][r] * ships[w][r] for w in range(len(warehouse_s)) for r in range(len(demands))])\n\n# Constraints for demands\nfor r in range(len(demands)):\n m += [sum([ships[w][r] for w in range(len(warehouse_s))]) == demands[r]]\n\n# Solve\nif m.solve():\n # Get the solution\n solution = {\n \"total_cost\": total_cost.value(),\n \"ships\": [[ships[w][r].value() for r in range(len(demands))] for w in range(len(warehouse_s))],\n \"open_warehouse\": [open_warehouse[w].value() for w in range(len(warehouse_s))]\n }\n print(json.dumps(solution, indent=4))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__fifty_puzzle", "model": "from cpmpy import *\nimport json\n\n# Data\ndummy_values = [15, 9, 30, 21, 19, 3, 12, 6, 25, 27]\n\n# Model\nx = boolvar(shape=len(dummy_values), name=\"x\")\n\nmodel = Model(\n [sum([x[i] * dummy_values[i] for i in range(len(dummy_values))]) == 50],\n [x]\n)\n\n# Solve\nif model.solve():\n # Get solution\n dummies = [i+1 for i, x_val in enumerate(x.value()) if x_val]\n print(json.dumps({\"dummies\": dummies}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__three_coins", "model": "from cpmpy import *\nimport json\n\n# Data\nnum_moves = 3\ninit = [1, 0, 1]\n\n# Model\ncoins = boolvar(shape=(num_moves+1, 3), name=\"coins\")\nmodel = Model()\n\n# Initial configuration\nfor i in range(3):\n model += [coins[0, i] == init[i]]\n\n# Transition constraints\nfor t in range(num_moves):\n model += [coins[t+1, 0] == coins[t, 0] ^ (coins[t, 1] & ~coins[t, 2])]\n model += [coins[t+1, 1] == coins[t, 1] ^ (coins[t, 0] & ~coins[t, 2])]\n model += [coins[t+1, 2] == coins[t, 2] ^ (coins[t, 0] & ~coins[t, 1])]\n\n# Goal constraints\nmodel += [coins[num_moves, 0] == coins[num_moves, 1]]\nmodel += [coins[num_moves, 1] == coins[num_moves, 2]]\n\n# Solve\nif model.solve():\n # Extract solution\n steps = []\n for t in range(num_moves):\n step = [int(coins[t+1, i].value()) for i in range(3)]\n steps.append(step)\n\n # Print solution as JSON\n print(json.dumps({\"steps\": steps}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__three_sum", "model": "from cpmpy import *\nimport json\n\n# Data\nnums = [-1, 6, 8, 9, 10, -100, 78, 0, 1]\n\n# Model\nmodel = Model()\n\n# Variables\nindices = [model.intvar(0, 1, name=f\"index_{i}\") for i in range(len(nums))]\n\n# Constraints\nmodel += (sum([nums[i] * indices[i] for i in range(len(nums))]) == 0)\nmodel += (sum(indices) == 3)\n\n# Solve\nif model.solve():\n # Extract solution\n indices_sol = [i for i, x in enumerate(indices) if x.value() == 1]\n\n # Print solution as JSON\n print(json.dumps({\"indices\": indices_sol}))\nelse:\n print(\"No solution found\")"} +{"id": "hakan_examples__twelve_pack", "model": "from cpmpy import *\nimport json\n\n# Data\ntarget = 20\n\n# Model\nx = intvar(0, target, name=\"x\") # Number of 7-packs\ny = intvar(0, target, name=\"y\") # Number of 13-packs\n\nmodel = Model(\n [7*x + 13*y >= target, \n (7*x + 13*y - target) == min([7*i + 13*j - target for i in range(target//7 + 1) for j in range(target//13 + 1) if 7*i + 13*j >= target])],\n minimize=False\n)\n\n# Solve\nif model.solve():\n counts = {\"7-packs\": x.value(), \"13-packs\": y.value()}\n print(json.dumps(counts))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__bus_scheduling", "model": "from cpmpy import *\nimport json\n\n# Input data\ndemands = [4, 8, 10, 7, 12, 4]\n\n# Model\nx = intvar(0, 100, shape=len(demands), name=\"x\")\n\n# Constraints\nmodel = Model(\n [x[i] >= demands[i] for i in range(len(demands))], # Meet demand in each interval\n [x[i] >= x[i-1] - 2 for i in range(1, len(demands))], # Account for overlapping shifts\n [x[i] >= x[i-2] for i in range(2, len(demands))], # Account for buses transitioning between intervals\n minimize=sum(x) # Minimize total number of buses\n)\n\n# Solve model\nif model.solve():\n # Print solution as JSON\n solution = {\"x\": [x[i].value() for i in range(len(demands))]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__jobshop", "model": "from cpmpy import *\nimport json\n\n# Input data\njobs_data = [\n [(0, 3), (1, 2), (2, 2)], # Job 0\n [(0, 2), (2, 1), (1, 4)], # Job 1\n [(1, 4), (2, 3)] # Job 2\n]\n\n# Model\nmodel = Model()\n\n# Decision variables\nnum_jobs = len(jobs_data)\nnum_machines = max(max(task[0] for task in job) for job in jobs_data) + 1\nnum_tasks = sum(len(job) for job in jobs_data)\n\ntask_start = [[Integer(0) for _ in range(len(jobs_data[j]))] for j in range(num_jobs)]\nmakespan = Integer(0)\n\n# Constraints\nfor j in range(num_jobs):\n for t in range(len(jobs_data[j]) - 1):\n model += task_start[j][t + 1] >= task_start[j][t] + jobs_data[j][t][1]\n\nfor m in range(num_machines):\n tasks_on_machine = []\n for j in range(num_jobs):\n for t, (machine, duration) in enumerate(jobs_data[j]):\n if machine == m:\n tasks_on_machine.append((task_start[j][t], duration))\n if tasks_on_machine:\n model += cumulative(tasks_on_machine, [1] * len(tasks_on_machine), 1)\n\nmodel += makespan >= max(task_start[j][-1] + jobs_data[j][-1][1] for j in range(num_jobs))\n\n# Objective\nmodel.minimize(makespan)\n\n# Solve\nstatus = model.solve()\n\n# Output\nif status:\n output = {\n \"makespan\": makespan.value()\n }\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__knapsack", "model": "from cpmpy import *\nimport json\n\n# Data\nvalues = [4, 2, 3, 7, 1]\nweights = [3, 1, 2, 5, 4]\ncapacity = 7\n\n# Model\nx = boolvar(shape=len(values), name=\"x\")\n\nmodel = Model(\n maximize=sum([values[i] * x[i] for i in range(len(values))]),\n [sum([weights[i] * x[i] for i in range(len(weights))]) <= capacity]\n)\n\n# Solve\nif model.solve():\n # Get the solution\n x_sol = [x[i].value() for i in range(len(x))]\n solution = {\n \"x\": x_sol\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__mario", "model": "from cpmpy import *\nimport json\n\n# Data\ndata = {\n 'nbHouses': 15,\n 'MarioHouse': 1,\n 'LuigiHouse': 2,\n 'fuelMax': 2000,\n 'goldTotalAmount': 1500,\n 'conso': [\n [0, 221, 274, 808, 13, 677, 670, 921, 943, 969, 13, 18, 217, 86, 322],\n [0, 0, 702, 83, 813, 679, 906, 246, 335, 529, 719, 528, 451, 242, 712],\n [274, 702, 0, 127, 110, 72, 835, 5, 161, 430, 686, 664, 799, 523, 73],\n [808, 83, 127, 0, 717, 80, 31, 71, 683, 668, 248, 826, 916, 467, 753],\n [13, 813, 110, 717, 0, 951, 593, 579, 706, 579, 101, 551, 280, 414, 294],\n [677, 679, 72, 80, 951, 0, 262, 12, 138, 222, 146, 571, 907, 225, 938],\n [670, 906, 835, 31, 593, 262, 0, 189, 558, 27, 287, 977, 226, 454, 501],\n [921, 246, 5, 71, 579, 12, 189, 0, 504, 221, 483, 226, 38, 314, 118],\n [943, 335, 161, 683, 706, 138, 558, 504, 0, 949, 393, 721, 267, 167, 420],\n [969, 529, 430, 668, 579, 222, 27, 221, 949, 0, 757, 747, 980, 589, 528],\n [13, 719, 686, 248, 101, 146, 287, 483, 393, 757, 0, 633, 334, 492, 859],\n [18, 528, 664, 826, 551, 571, 977, 226, 721, 747, 633, 0, 33, 981, 375],\n [217, 451, 799, 916, 280, 907, 226, 38, 267, 980, 334, 33, 0, 824, 491],\n [86, 242, 523, 467, 414, 225, 454, 314, 167, 589, 492, 981, 824, 0, 143],\n [322, 712, 73, 753, 294, 938, 501, 118, 420, 528, 859, 375, 491, 143, 0]\n ],\n 'goldInHouse': [0, 0, 40, 67, 89, 50, 6, 19, 47, 68, 94, 86, 34, 14, 14]\n}\n\n# Model\nmodel = Model()\n\n# Variables\ns = intvar(0, data['nbHouses']-1, shape=data['nbHouses'], name='s')\n\n# Constraints\nmodel += [s[0] == data['MarioHouse']-1]\nmodel += [s[-1] == data['LuigiHouse']-1]\nmodel += [AllDifferent(s)]\n\nfuel_consumed = sum([data['conso'][s[i]][s[i+1]] for i in range(data['nbHouses']-1)])\nmodel += [fuel_consumed <= data['fuelMax']]\n\n# Objective\ngold_collected = sum([data['goldInHouse'][s[i]] for i in range(data['nbHouses'])])\nmodel.maximize(gold_collected)\n\n# Solve\nif model.solve():\n solution = {'s': [int(x) for x in s.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__minesweeper", "model": "from cpmpy import *\nimport json\n\n# Data\ngame_data = [\n [2, 3, -1, 2, 2, -1, 2, 1],\n [-1, -1, 4, -1, -1, 4, -1, 2],\n [-1, -1, -1, -1, -1, -1, 4, -1],\n [-1, 5, -1, 6, -1, -1, -1, 2],\n [2, -1, -1, -1, 5, 5, -1, 2],\n [1, 3, 4, -1, -1, -1, 4, -1],\n [0, 1, -1, 4, -1, -1, -1, 3],\n [0, 1, 2, -1, 2, 3, -1, 2]\n]\n\n# Model\nmodel = Model()\n\n# Variables\nmines = [[Bool(\"mine_%i_%i\" % (i, j)) for j in range(len(game_data[0]))] for i in range(len(game_data))]\n\n# Constraints\nfor i in range(len(game_data)):\n for j in range(len(game_data[0])):\n if game_data[i][j] != -1:\n adj_mines = 0\n for x in range(max(0, i-1), min(len(game_data), i+2)):\n for y in range(max(0, j-1), min(len(game_data[0]), j+2)):\n if (x, y) != (i, j):\n adj_mines += mines[x][y]\n model += adj_mines == game_data[i][j]\n\n# Solve\nif model.solve():\n # Extract solution\n solution = [[mines[i][j].value() for j in range(len(game_data[0]))] for i in range(len(game_data))]\n \n # Print solution as JSON\n print(json.dumps({\"mines\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__n_puzzle", "model": "from cpmpy import *\nimport json\nimport numpy as np\n\n# Define the input data\nN = 20\npuzzle_start = np.array([\n [0, 3, 6],\n [2, 4, 8],\n [1, 7, 5]\n])\npuzzle_end = np.array([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 0]\n])\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nsteps = []\nfor i in range(N+1):\n step = intvar(0, 8, shape=(3, 3), name=f\"step_{i}\")\n steps.append(step)\n\n# Define the constraints\nmodel += [steps[0] == puzzle_start]\nfor i in range(N):\n model += [steps[i+1][0, 0] == steps[i][0, 0] + \n steps[i][0, 1] == steps[i+1][0, 1] + \n steps[i][0, 2] == steps[i+1][0, 2] + \n steps[i][1, 0] == steps[i+1][1, 0] + \n steps[i][1, 1] == steps[i+1][1, 1] + \n steps[i][1, 2] == steps[i+1][1, 2] + \n steps[i][2, 0] == steps[i+1][2, 0] + \n steps[i][2, 1] == steps[i+1][2, 1] + \n steps[i][2, 2] == steps[i+1][2, 2]]\n # Only one move per step\n model += [sum([steps[i][j, k] != steps[i+1][j, k] for j in range(3) for k in range(3)]) == 1]\n # Only move adjacent tiles\n for j in range(3):\n for k in range(3):\n if j > 0:\n model += [steps[i][j, k] != steps[i+1][j-1, k]]\n if j < 2:\n model += [steps[i][j, k] != steps[i+1][j+1, k]]\n if k > 0:\n model += [steps[i][j, k] != steps[i+1][j, k-1]]\n if k < 2:\n model += [steps[i][j, k] != steps[i+1][j, k+1]]\n\nmodel += [steps[N] == puzzle_end]\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = []\n for step in steps:\n solution.append(step.value())\n print(json.dumps({\"steps\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__packing_rectangles", "model": "from cpmpy import *\nimport json\n\n# Data\nwidths = [3, 4, 2, 1]\nheights = [2, 3, 1, 4]\nn = len(widths)\n\n# Model\nx = intvar(0, 100, shape=n, name=\"x\")\ny = intvar(0, 100, shape=n, name=\"y\")\ntotal_x = intvar(0, 100, name=\"total_x\")\ntotal_y = intvar(0, 100, name=\"total_y\")\n\nmodel = Model(\n [total_x >= x[i] + widths[i] for i in range(n)],\n [total_y >= y[i] + heights[i] for i in range(n)],\n [x[i] + widths[i] <= total_x for i in range(n)],\n [y[i] + heights[i] <= total_y for i in range(n)],\n [x[i] >= 0 for i in range(n)],\n [y[i] >= 0 for i in range(n)],\n [~(x[i] < x[j] & x[j] < x[i] + widths[i] & y[i] < y[j] + heights[j] & y[j] < y[i] + heights[i]) \n for i in range(n) for j in range(i+1, n)],\n [~(x[i] < x[j] + widths[j] & x[j] + widths[j] < x[i] + widths[i] & y[i] < y[j] + heights[j] & y[j] < y[i] + heights[i]) \n for i in range(n) for j in range(i+1, n)],\n [~(y[i] < y[j] & y[j] < y[i] + heights[i] & x[i] < x[j] + widths[j] & x[j] + widths[j] < x[i] + widths[i]) \n for i in range(n) for j in range(i+1, n)],\n [~(y[i] < y[j] + heights[j] & y[j] + heights[j] < y[i] + heights[i] & x[i] < x[j] + widths[j] & x[j] + widths[j] < x[i] + widths[i]) \n for i in range(n) for j in range(i+1, n)],\n minimize=total_x*total_y\n)\n\n# Solve\nif model.solve():\n solution = {\n \"total_y\": total_y.value(),\n \"pos_x\": [x[i].value() for i in range(n)],\n \"pos_y\": [y[i].value() for i in range(n)],\n \"total_x\": total_x.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__resource_constrained_project_scheduling", "model": "from cpmpy import *\nimport json\n\n# Data\nnum_jobs = 12\ndurations_data = [0, 3, 2, 5, 4, 2, 3, 4, 2, 4, 6, 0]\nresource_needs_data = [[0, 0], [5, 1], [0, 4], [1, 4], [1, 3], [3, 2], [3, 1], [2, 4], [4, 0], [5, 2], [2, 5], [0, 0]]\nresource_capacities_data = [6, 8]\nsuccessors_link_data = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 9], [2, 10], [3, 8], [4, 6], [4, 7], [5, 9], [5, 10], [6, 8], [6, 9], [7, 8], [8, 11], [9, 11], [10, 11]]\n\n# Model\nmodel = Model()\n\n# Variables\nstart_time = intvar(0, 100, shape=num_jobs, name=\"start_time\")\n\n# Constraints\nfor i in range(num_jobs):\n for j in range(num_jobs):\n if [i, j] in successors_link_data:\n model += start_time[j] >= start_time[i] + durations_data[i]\n\nfor t in range(100):\n for res in range(2):\n sum_resources = 0\n for i in range(num_jobs):\n model += ((start_time[i] <= t) & (start_time[i] + durations_data[i] > t)) <= (sum_resources + resource_needs_data[i][res] <= resource_capacities_data[res])\n sum_resources += resource_needs_data[i][res]\n\n# Objective\nmakespan = intvar(0, 100, name=\"makespan\")\nmodel += makespan == max(start_time[i] + durations_data[i] for i in range(num_jobs))\nmodel.minimize(makespan)\n\n# Solve\nif model.solve():\n solution = {f\"start_time_{i}\": start_time[i].value() for i in range(num_jobs)}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__room_assignment", "model": "from cpmpy import *\nimport json\nfrom datetime import datetime\n\n# Data\nmax_rooms = 5\nstart_data = [\"2024-05-01\", \"2024-05-02\", \"2024-05-03\", \"2024-05-04\"]\nend_data = [\"2024-05-05\", \"2024-05-06\", \"2024-05-07\", \"2024-05-08\"]\npreassigned_room_data = [3, -1, -1, -1]\n\n# Convert date strings to integers for easier comparison\nstart_dates = [int(datetime.strptime(date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")) for date in start_data]\nend_dates = [int(datetime.strptime(date, \"%Y-%m-%d\").strftime(\"%Y%m%d\")) for date in end_data]\n\n# Model\nmodel = Model()\n\n# Decision variables\nroom_assignments = intvar(1, max_rooms, shape=len(start_data), name=\"room_assignments\")\n\n# Constraints\nfor i in range(len(start_data)):\n if preassigned_room_data[i] != -1:\n model += (room_assignments[i] == preassigned_room_data[i])\n\nfor i in range(len(start_data)):\n for j in range(i+1, len(start_data)):\n model += ((room_assignments[i] != room_assignments[j]) | \n (start_dates[i] >= end_dates[j]) | \n (start_dates[j] >= end_dates[i]))\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\"room_assignments\": [room_assignments[i].value() for i in range(len(start_data))]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found.\")"} +{"id": "cpmpy_examples__send_more_money", "model": "from cpmpy import *\nimport json\n\n# Define the variables\ns, e, n, d, m, o, r, y = intvar(0, 9, shape=8, name=\"send_more_money\")\n\n# Define the constraints\nmodel = Model(\n AllDifferent([s, e, n, d, m, o, r, y]), # All letters must be unique\n s > 0, # First letter of SEND cannot be zero\n m > 0, # First letter of MORE cannot be zero\n (1000 * s + 100 * e + 10 * n + d) + (1000 * m + 100 * o + 10 * r + e) == (10000 * m + 1000 * o + 100 * n + 10 * e + y),\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as JSON\n solution = {\n \"y\": y.value(),\n \"e\": e.value(),\n \"s\": s.value(),\n \"r\": r.value(),\n \"o\": o.value(),\n \"d\": d.value(),\n \"m\": m.value(),\n \"n\": n.value(),\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__set_game", "model": "from cpmpy import *\nimport json\n\n# Constants\nONE, TWO, THREE = 1, 2, 3\nRED, PURPLE, GREEN = 1, 2, 3\nDIAMOND, RECT, ELLIPSE = 1, 2, 3\nFULL, EMPTY, STRIPED = 1, 2, 3\n\n# Make the card deck\ncards_data = [\n [ONE, EMPTY, GREEN, DIAMOND],\n [TWO, STRIPED, RED, RECT],\n [THREE, STRIPED, GREEN, DIAMOND],\n [THREE, FULL, RED, DIAMOND],\n [ONE, STRIPED, GREEN, DIAMOND],\n [ONE, EMPTY, RED, DIAMOND],\n [TWO, FULL, PURPLE, DIAMOND],\n [THREE, FULL, PURPLE, ELLIPSE],\n [THREE, FULL, GREEN, RECT],\n [ONE, FULL, PURPLE, DIAMOND],\n [ONE, STRIPED, PURPLE, DIAMOND],\n [ONE, FULL, GREEN, RECT]\n]\n\n# Model\nmodel = Model()\n\n# Decision variables\nwinning_cards = intvar(0, len(cards_data) - 1, shape=3, name=\"winning_cards\")\n\n# Constraints\nfor i in range(3):\n model += [winning_cards[i] >= 0, winning_cards[i] < len(cards_data)]\n\nmodel += [AllDifferent(winning_cards)]\n\nfor f in range(4):\n same_feature = [cards_data[winning_cards[i]][f] for i in range(3)]\n model += [AllEqual(same_feature) | AllDifferent(same_feature)]\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\"winning_cards\": [int(x.value()) for x in winning_cards]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__sudoku", "model": "from cpmpy import *\nimport json\n\ninput_grid = [\n [0, 0, 0, 2, 0, 5, 0, 0, 0],\n [0, 9, 0, 0, 0, 0, 7, 3, 0],\n [0, 0, 2, 0, 0, 9, 0, 6, 0],\n [2, 0, 0, 0, 0, 0, 4, 0, 9],\n [0, 0, 0, 0, 7, 0, 0, 0, 0],\n [6, 0, 9, 0, 0, 0, 0, 0, 1],\n [0, 8, 0, 4, 0, 0, 1, 0, 0],\n [0, 6, 3, 0, 0, 0, 0, 8, 0],\n [0, 0, 0, 6, 0, 8, 0, 0, 0]\n]\n\n# Model\nmodel = Model()\n\n# Variables\ngrid = [[intvar(1, 9, name=f\"g_{i}_{j}\") if input_grid[i][j] == 0 else input_grid[i][j] for j in range(9)] for i in range(9)]\n\n# Constraints\nfor i in range(9):\n model += AllDifferent([grid[i][j] for j in range(9)])\n model += AllDifferent([grid[j][i] for j in range(9)])\n\nfor i in range(0, 9, 3):\n for j in range(0, 9, 3):\n model += AllDifferent([grid[x][y] for x in range(i, i+3) for y in range(j, j+3)])\n\nfor i in range(9):\n for j in range(9):\n if input_grid[i][j] != 0:\n model += grid[i][j] == input_grid[i][j]\n\n# Solve\nif model.solve():\n solution = [[int(grid[i][j].value()) for j in range(9)] for i in range(9)]\n print(json.dumps({\"grid\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__tsp", "model": "from cpmpy import *\nimport math\nimport json\n\n# Define the locations\nlocations = [(288, 149), (288, 129), (270, 133), (256, 141), (256, 163), (246, 157), (236, 169), (228, 169), (228, 148), (220, 164), (212, 172), (204, 159)]\n\n# Define the number of cities\nn = len(locations)\n\n# Define the distance matrix\ndistances = [[0 for _ in range(n)] for _ in range(n)]\nfor i in range(n):\n for j in range(n):\n distances[i][j] = math.sqrt((locations[i][0] - locations[j][0])**2 + (locations[i][1] - locations[j][1])**2)\n\n# Define the model\nmodel = Model()\n\n# Define the variables\nx = [[Boolean() for _ in range(n)] for _ in range(n)]\n\n# Define the constraints\nfor i in range(n):\n model += sum([x[i][j] for j in range(n)]) == 1\n model += sum([x[j][i] for j in range(n)]) == 1\n\nfor i in range(n):\n for j in range(n):\n if i == j:\n model += x[i][j] == 0\n\nfor i in range(n):\n for j in range(n):\n for k in range(n):\n if i != j and j != k and k != i:\n model += x[i][j] + x[j][k] <= 1 + x[k][i]\n\n# Define the objective function\ntravel_distance = Int()\nmodel += travel_distance == sum([distances[i][j] * x[i][j] for i in range(n) for j in range(n)])\n\n# Add a constraint to close the loop\nmodel += sum([x[i][0] for i in range(1, n)]) == 1\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"travel_distance\": travel_distance.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__who_killed_agatha", "model": "from cpmpy import *\nimport json\n\n# Data\nnames = [\"Agatha herself\", \"the butler\", \"Charles\"]\n\n# Variables\nkiller = int_var(0, 2, name=\"killer\")\n\n# Constraints\n# Agatha hates everybody except the butler\nagatha_hates = [1, 2] # indices of people Agatha hates\n# The butler hates everyone not richer than Aunt Agatha\nbutler_hates = [0, 2] # indices of people the butler hates\n# The butler hates everyone whom Agatha hates\n# This is already included in butler_hates\n# Charles hates noone that Agatha hates\ncharles_hates = [] # indices of people Charles hates\n\n# Model\nmodel = Model(\n # A killer always hates, and is no richer than his victim\n [killer in agatha_hates, \n killer != 0], # Agatha cannot kill herself\n # Additional constraints based on the problem description\n [killer in butler_hates if killer == 1 else True], # butler hates everyone not richer than Agatha\n [killer not in agatha_hates if killer == 2 else True] # Charles hates noone that Agatha hates\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\"killer\": names[killer.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__wolf_goat_cabbage", "model": "from cpmpy import *\nimport json\n\n# Define the number of stages\nstage = 8\n\n# Define the decision variables\nwolf_pos = boolvar(shape=stage+1, name=\"wolf_pos\")\ngoat_pos = boolvar(shape=stage+1, name=\"goat_pos\")\ncabbage_pos = boolvar(shape=stage+1, name=\"cabbage_pos\")\nboat_pos = boolvar(shape=stage+1, name=\"boat_pos\")\n\n# Model\nmodel = Model(\n # Initial positions\n wolf_pos[0] == 0,\n goat_pos[0] == 0,\n cabbage_pos[0] == 0,\n boat_pos[0] == 0,\n\n # Final positions\n wolf_pos[stage] == 1,\n goat_pos[stage] == 1,\n cabbage_pos[stage] == 1,\n boat_pos[stage] == 1,\n\n # Boat movement\n [boat_pos[t] != boat_pos[t+1] for t in range(stage)],\n\n # Farmer is with the boat\n [wolf_pos[t] == boat_pos[t] or goat_pos[t] == boat_pos[t] or cabbage_pos[t] == boat_pos[t] for t in range(1, stage+1)],\n\n # Wolf and goat are not left together\n [(wolf_pos[t] != goat_pos[t]) or boat_pos[t] == wolf_pos[t] or boat_pos[t] == goat_pos[t] for t in range(1, stage+1)],\n\n # Goat and cabbage are not left together\n [(goat_pos[t] != cabbage_pos[t]) or boat_pos[t] == goat_pos[t] or boat_pos[t] == cabbage_pos[t] for t in range(1, stage+1)],\n\n # Wolf and cabbage are not left together (this constraint is not necessary, but it helps the solver)\n [(wolf_pos[t] != cabbage_pos[t]) or boat_pos[t] == wolf_pos[t] or boat_pos[t] == cabbage_pos[t] for t in range(1, stage+1)]\n)\n\n# Solve the model\nif model.solve():\n # Create the solution dictionary\n solution = {\n \"boat_pos\": [int(boat_pos[t].value()) for t in range(stage+1)],\n \"0\": 0,\n \"cabbage_pos\": [int(cabbage_pos[t].value()) for t in range(stage+1)],\n \"goat_pos\": [int(goat_pos[t].value()) for t in range(stage+1)],\n \"wolf_pos\": [int(wolf_pos[t].value()) for t in range(stage+1)],\n \"1\": 1\n }\n\n # Print the solution as a JSON object\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "cpmpy_examples__zebra", "model": "from cpmpy import *\nimport json\n\n# Define the variables\ncolors = [\"yellow\", \"green\", \"red\", \"white\", \"blue\"]\nnations = [\"italy\", \"spain\", \"japan\", \"england\", \"norway\"]\njobs = [\"painter\", \"sculptor\", \"diplomat\", \"pianist\", \"doctor\"]\npets = [\"cat\", \"zebra\", \"bear\", \"snails\", \"horse\"]\ndrinks = [\"milk\", \"water\", \"tea\", \"coffee\", \"juice\"]\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\ncolor_vars = intvar(1, 5, shape=5, name=\"color\")\nnation_vars = intvar(1, 5, shape=5, name=\"nation\")\njob_vars = intvar(1, 5, shape=5, name=\"job\")\npet_vars = intvar(1, 5, shape=5, name=\"pet\")\ndrink_vars = intvar(1, 5, shape=5, name=\"drink\")\n\n# Constraints\nmodel += [AllDifferent(color_vars)]\nmodel += [AllDifferent(nation_vars)]\nmodel += [AllDifferent(job_vars)]\nmodel += [AllDifferent(pet_vars)]\nmodel += [AllDifferent(drink_vars)]\n\n# The painter owns the horse\nmodel += [job_vars[0] == 1, pet_vars[0] == 5]\n\n# The diplomat drinks coffee\nmodel += [job_vars[2] == 3, drink_vars[2] == 4]\n\n# The one who drinks milk lives in the white house\nmodel += [drink_vars[3] == 1, color_vars[3] == 4]\n\n# The Spaniard is a painter\nmodel += [nation_vars[1] == 2, job_vars[1] == 1]\n\n# The Englishman lives in the red house\nmodel += [nation_vars[3] == 4, color_vars[3] == 3]\n\n# The snails are owned by the sculptor\nmodel += [pet_vars[2] == 4, job_vars[2] == 2]\n\n# The green house is on the left of the red one\nmodel += [color_vars[1] == 2, color_vars[2] == 3]\n\n# The Norwegian lives on the right of the blue house\nmodel += [color_vars[4] == 5, nation_vars[4] == 5]\n\n# The doctor drinks milk\nmodel += [job_vars[4] == 5, drink_vars[4] == 1]\n\n# The diplomat is Japanese\nmodel += [nation_vars[2] == 3, job_vars[2] == 3]\n\n# The Norwegian owns the zebra\nmodel += [pet_vars[4] == 2, nation_vars[4] == 5]\n\n# The green house is next to the white one\nmodel += [color_vars[2] == 2, color_vars[3] == 4]\n\n# The horse is owned by the neighbor of the diplomat\nmodel += [pet_vars[1] == 5, job_vars[2] == 3]\n\n# The Italian either lives in the red, white or green house\nmodel += [Or([nation_vars[1] == 1, nation_vars[2] == 1, nation_vars[3] == 1])]\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"colors\": [colors[i-1] for i in color_vars.value()],\n \"jobs\": [jobs[i-1] for i in job_vars.value()],\n \"nations\": [nations[i-1] for i in nation_vars.value()],\n \"pets\": [pets[i-1] for i in pet_vars.value()],\n \"drinks\": [drinks[i-1] for i in drink_vars.value()]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__bank_card", "model": "from cpmpy import *\nimport json\n\n# Define the model\na, b, c, d = int_var(0, 9), int_var(0, 9), int_var(0, 9), int_var(0, 9)\n\nmodel = Model(\n [a != b, a != c, a != d, b != c, b != d, c != d], # all digits are different\n [10*a + b <= 9*10 + 9], # ab is at most 99\n [10*c + d <= 9*10 + 9], # cd is at most 99\n [10*d + a <= 9*10 + 9], # da is at most 99\n [10*b + c <= 9*10 + 9], # bc is at most 99\n [3*(10*a + b) == (10*c + d)], # cd is 3 times ab\n [2*(10*b + c) == (10*d + a)], # da is 2 times bc\n)\n\n# Solve the model\nif model.solve():\n solution = {\"a\": a.value(), \"b\": b.value(), \"c\": c.value(), \"d\": d.value()}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__climbing_stairs", "model": "from cpmpy import *\nimport json\n\n# Define the model\nn = 20 # Total steps\nm1 = 3 # Minimum steps at a time\nm2 = 5 # Maximum steps at a time\n\n# Define the variable\nsteps = intvar(0, m2, shape=n)\n\n# Define the model\nmodel = Model(\n # Objective: sum of steps equals n\n [sum(steps) == n],\n # Each step is between m1 and m2 (inclusive) or 0\n [steps[i] in [0, m1, m2] for i in range(n)],\n # Cumulative sum of steps does not exceed n at any point\n [cumsum(steps[:i+1]) <= n for i in range(n)],\n # If a step is not 0, it must be m1 or m2\n [steps[i] >= m1 for i in range(n)]\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n print(json.dumps({\"steps\": [steps[i].value() for i in range(n)]}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__color_simple", "model": "from cpmpy import *\nimport json\n\n# Define the adjacency list\ngraph = [\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\n# Define the number of countries\nnum_countries = len(graph)\n\n# Define the number of colors\nnum_colors = num_countries\n\n# Define the color variables\ncolors = intvar(1, num_colors, shape=num_countries, name=\"colors\")\n\n# Define the model\nmodel = Model()\n\n# Add constraints: two neighbouring countries cannot have the same color\nfor i in range(num_countries):\n for j in graph[i]:\n model += colors[i] != colors[j-1]\n\n# Solve the model\nif model.solve():\n # Print the colors assigned to each country as a JSON object\n output = {\"colors\": [int(c) for c in colors.value()]}\n print(json.dumps(output))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__exodus", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nages = [3, 5, 7, 8, 10]\nchildren = [\"Bernice\", \"Carl\", \"Debby\", \"Sammy\", \"Ted\"]\ncountries = [\"Ethiopia\", \"Kazakhstan\", \"Lithuania\", \"Morocco\", \"Yemen\"]\nstories = [\"burning bush\", \"captivity\", \"Moses\u2019s youth\", \"Passover\", \"Ten Commandments\"]\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\nchild = intvar(1, 5, shape=5, name=\"child\")\ncountry = intvar(1, 5, shape=5, name=\"country\")\nstory = intvar(1, 5, shape=5, name=\"story\")\nage = intvar(1, 5, shape=5, name=\"age\")\n\n# Constraints\nmodel += [AllDifferent(child)]\nmodel += [AllDifferent(country)]\nmodel += [AllDifferent(story)]\nmodel += [AllDifferent(age)]\n\n# Debby\u2019s family is from Lithuania\nmodel += [country[children.index(\"Debby\")] == countries.index(\"Lithuania\") + 1]\n\n# The child who told the story of the Passover is two years older than Bernice\nmodel += [age[stories.index(\"Passover\")] - age[children.index(\"Bernice\")] == 2]\n\n# The child whose family is from Yemen is younger than the child from the Ethiopian family\nmodel += [age[countries.index(\"Yemen\")] < age[countries.index(\"Ethiopia\")]]\n\n# The child from the Moroccan family is three years older than Ted\nmodel += [age[countries.index(\"Morocco\")] - age[children.index(\"Ted\")] == 3]\n\n# Sammy is three years older than the child who told the story of Moses\u2019s youth\nmodel += [age[children.index(\"Sammy\")] - age[stories.index(\"Moses\u2019s youth\")] == 3]\n\n# Solve the model\nif model.solve():\n # Get the solution\n child_sol = [child[i].value() for i in range(5)]\n country_sol = [country[i].value() for i in range(5)]\n story_sol = [story[i].value() for i in range(5)]\n age_sol = [age[i].value() for i in range(5)]\n\n # Map the solution to the original lists\n countries_sol = [countries[i-1] for i in country_sol]\n children_sol = [children[i-1] for i in child_sol]\n stories_sol = [stories[i-1] for i in story_sol]\n ages_sol = [ages[i-1] for i in age_sol]\n\n # Print the solution as a JSON object\n print(json.dumps({\n \"countries\": [countries.index(c) + 1 for c in countries_sol],\n \"children\": [children.index(c) + 1 for c in children_sol],\n \"stories\": [stories.index(s) + 1 for s in stories_sol],\n \"ages\": [ages.index(a) + 1 for a in ages_sol]\n }))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__farmer_and_cows", "model": "from cpmpy import *\nimport json\n\n# Data\nnum_cows = 25\nnum_sons = 5\ncows_per_son = [7, 6, 5, 4, 3]\nmilk_per_cow = list(range(1, num_cows + 1))\n\n# Model\nmodel = Model()\n\n# Variables\ncow_assignments = intvar(0, num_sons - 1, shape=num_cows, name=\"cow_assignments\")\n\n# Constraints\nfor i, num in enumerate(cows_per_son):\n model += sum([cow_assignments[j] == i for j in range(num_cows)]) == num\n\nmilk_per_son = [[milk_per_cow[j] for j in range(num_cows) if cow_assignments[j] == i] for i in range(num_sons)]\nfor i in range(1, num_sons):\n model += sum(milk_per_cow[j] for j in range(num_cows) if cow_assignments[j] == 0) == sum(milk_per_cow[j] for j in range(num_cows) if cow_assignments[j] == i)\n\n# Solve\nif model.solve():\n solution = {\"cow_assignments\": [int(x.value()) for x in cow_assignments]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__five_floors", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nB = int_var(1, 5, name=\"B\")\nC = int_var(1, 5, name=\"C\")\nF = int_var(1, 5, name=\"F\")\nM = int_var(1, 5, name=\"M\")\nS = int_var(1, 5, name=\"S\")\n\n# Define the model\nmodel = Model(\n [B != 5, # Baker does not live on the fifth floor\n C != 1, # Cooper does not live on the first floor\n F != 1, F != 5, # Fletcher does not live on either the fifth or the first floor\n M > C, # Miller lives on a higher floor than does Cooper\n abs(S - F) > 1, # Smith does not live on a floor adjacent to Fletcher's\n abs(F - C) > 1, # Fletcher does not live on a floor adjacent to Cooper's\n AllDifferent([B, C, F, M, S]) # They all live on different floors\n ]\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"B\": B.value(), \"C\": C.value(), \"F\": F.value(), \"M\": M.value(), \"S\": S.value()}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__grocery", "model": "from cpmpy import *\nimport json\n\n# Define the model\nx = intvar(1, 100, shape=4, name=\"prices\")\n\n# Define the constraints\nmodel = Model(\n [x[0] * x[1] * x[2] * x[3] == 711],\n [sum(x) == 711]\n)\n\n# Solve the model\nif model.solve():\n # Get the solution\n solution = {f\"prices[{i}]\": x[i].value() for i in range(4)}\n solution[\"prices\"] = [x[i].value() for i in range(4)]\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__guards_and_apples", "model": "from cpmpy import *\nimport json\n\n# Define the model\nx = intvar(1, 1000, shape=6, name=\"apples\")\n\n# Define the model constraints\nmodel = Model(\n [x[i] == (x[i-1] + 1) // 2 + (x[i-1] + 1) % 2 for i in range(1, 6)],\n [x[5] == 1]\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n print(json.dumps({\"apples\": [int(val) for val in x.value]}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__hardy_1729_square", "model": "from cpmpy import *\nimport json\n\n# Model\na, b, c, d = intvar(1, 100, shape=4, name=\"vars\")\n\n# Constraints\nmodel = Model(\n AllDifferent([a, b, c, d]),\n a**2 + b**2 == c**2 + d**2\n)\n\n# Solve\nif model.solve():\n solution = {\n \"a\": a.value(),\n \"b\": b.value(),\n \"c\": c.value(),\n \"d\": d.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__kidney_exchange", "model": "from cpmpy import *\nimport json\n\n# Data\nnum_people = 8\ncompatible = [\n [2, 3],\n [1, 6],\n [1, 4, 7],\n [2],\n [2],\n [5],\n [8],\n [3]\n]\n\n# Model\nmodel = Model()\n\n# Variable: transplants[i][j] is 1 if person i donates to person j, and 0 otherwise\ntransplants = [[model.new_int(var=0, name=f\"transplants_{i}_{j}\") for j in range(num_people)] for i in range(num_people)]\n\n# Constraints\nfor i in range(num_people):\n for j in range(num_people):\n model += [transplants[i][j] == 1].only_if(compatible[i].__contains__(j + 1))\n\nfor i in range(num_people):\n model += sum(transplants[i]) <= 1 # person i donates to at most one person\n model += sum([transplants[j][i] for j in range(num_people)]) <= 1 # person i receives at most one kidney\n\nfor i in range(num_people):\n model += sum(transplants[i]) == sum([transplants[j][i] for j in range(num_people)]) # person i donates if and only if they receive\n\n# Objective\nmodel.maximize(sum([sum(transplants[i]) for i in range(num_people)]))\n\n# Solve\nif model.solve():\n # Extract solution\n transplants_solution = [[transplants[i][j].value() for j in range(num_people)] for i in range(num_people)]\n\n # Print solution as JSON\n print(json.dumps({\"transplants\": transplants_solution}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__magic_square", "model": "from cpmpy import *\nimport json\n\n# Define the size of the magic square\nn = 4\n\n# Define the sum of integers in each row, column and diagonal\ntarget_sum = n * (n**2 + 1) // 2\n\n# Define the variables\nx = intvar(1, n**2, shape=(n, n), name=\"x\")\n\n# Define the model\nmodel = Model()\n\n# Each cell contains a different integer\nmodel += AllDifferent(x.flatten())\n\n# The sum of integers in each row is equal to the target sum\nfor i in range(n):\n model += sum(x[i, :]) == target_sum\n\n# The sum of integers in each column is equal to the target sum\nfor j in range(n):\n model += sum(x[:, j]) == target_sum\n\n# The sum of integers in the main diagonal is equal to the target sum\nmodel += sum([x[i, i] for i in range(n)]) == target_sum\n\n# The sum of integers in the anti-diagonal is equal to the target sum\nmodel += sum([x[i, n-i-1] for i in range(n)]) == target_sum\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = x.value()\n print(json.dumps({\"square\": [list(row) for row in solution]}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__maximal_independent_sets", "model": "from cpmpy import *\nimport json\n\n# Data\nn = 8\nadjacency_list = [\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\n# Model\nmodel = Model()\n\n# Variables\nx = boolvar(shape=n, name=\"x\")\n\n# Constraints\nfor i in range(n):\n for j in adjacency_list[i]:\n model += ~x[i] | ~x[j-1] # subtract 1 because adjacency list is 1-indexed\n\n# Objective: maximize the number of nodes in the independent set\nmodel.maximize(sum(x))\n\n# Solve\nif model.solve():\n # Get the solution\n solution = {f\"node_{i+1}\": bool(x[i].value()) for i in range(n)}\n print(json.dumps({\"nodes\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__money_change", "model": "from cpmpy import *\nimport json\n\n# Define the available coins and their counts\ncoin_values = [1, 2, 5, 10, 25, 50]\ncoin_counts_available = [20, 10, 15, 8, 4, 2]\n\n# Define the target change\nchange = 199\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\ncoin_counts = intvar(0, max(coin_counts_available), shape=len(coin_values), name=\"coin_counts\")\n\n# Define the constraints\nmodel += (sum([coin_values[i] * coin_counts[i] for i in range(len(coin_values))]) == change)\nfor i in range(len(coin_values)):\n model += (coin_counts[i] <= coin_counts_available[i])\n\n# Define the objective\nmodel.minimize(sum(coin_counts))\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\"coin_counts\": [int(x) for x in coin_counts.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__movie_scheduling", "model": "from cpmpy import *\nimport json\n\n# Input data\nmovies = [\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\n# Sort movies by end date\nmovies.sort(key=lambda x: x[2])\n\n# Model\nmodel = Model()\n\n# Decision variables\nselected_movies = [model.bool_var() for _ in range(len(movies))]\n\n# Constraints\nfor i in range(len(movies)):\n for j in range(i+1, len(movies)):\n model.add(selected_movies[i] + selected_movies[j] <= (movies[j][1] > movies[i][2]))\n\n# Objective\nmodel.maximize(sum(selected_movies))\n\n# Solve\nif model.solve():\n num_selected_movies = sum([int(var.value()) for var in selected_movies])\n solution = {\n \"selected_movies\": [int(var.value()) for var in selected_movies],\n \"num_selected_movies\": num_selected_movies\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__people_in_a_room", "model": "from cpmpy import *\nimport json\n\n# Model\nnum_people = 13\nnum_males = 4\nnum_females = num_people - num_males\n\n# Decision variable: sequence of people entering the room (0 = male, 1 = female)\nsequence = intvar(0, 1, shape=num_people, name=\"sequence\")\n\n# Constraints\nmodel = Model(\n # Exactly num_males males and num_females females\n sum(sequence) == num_females,\n # Ratio of females to males at any time is no greater than 7/3\n [sum(sequence[:i+1]) / (i + 1 - sum(sequence[:i+1])) <= 7/3 for i in range(num_people)]\n)\n\n# Solve\nif model.solve():\n # Print solution as JSON\n solution = {\"sequence\": [int(x) for x in sequence.value()]}\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__subsets_100", "model": "from cpmpy import *\nimport json\n\n# Define the set of integers\nA = [81, 21, 79, 4, 29, 70, 28, 20, 14, 7]\n\n# Define the model\nmodel = Model()\n\n# Define the decision variables\nin_S = boolvar(shape=len(A), name=\"in_S\")\nin_T = boolvar(shape=len(A), name=\"in_T\")\n\n# Define the constraints\nmodel += [sum([A[i] * in_S[i] for i in range(len(A))]) == sum([A[i] * in_T[i] for i in range(len(A))])]\nmodel += [(in_S[i] + in_T[i]) <= 1 for i in range(len(A))]\nmodel += [sum(in_S) > 0]\nmodel += [sum(in_T) > 0]\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {\n \"in_S\": [int(in_S[i].value()) for i in range(len(A))],\n \"in_T\": [int(in_T[i].value()) for i in range(len(A))]\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__subset_sum", "model": "from cpmpy import *\nimport json\n\n# Define the possible number of coins in each bag\ncoin_values = [16, 17, 23, 24, 39, 40]\n\n# Define the number of coins lost\ntotal_coins_lost = 100\n\n# Define the decision variables\nbags = intvar(0, 100, shape=len(coin_values), name=\"bags\")\n\n# Define the model\nmodel = Model(\n sum([coin_values[i] * bags[i] for i in range(len(coin_values))]) == total_coins_lost\n)\n\n# Solve the model\nif model.solve():\n # Print the solution as a JSON object\n solution = {f\"bags_{i}\": bags[i].value() for i in range(len(coin_values))}\n print(json.dumps({\"bags\": solution}))\nelse:\n print(\"No solution found\")"} +{"id": "aplai_course__thick_as_thieves", "model": "from cpmpy import *\nimport json\n\n# Define the variables\nartie = boolvar(name=\"artie\")\nbill = boolvar(name=\"bill\")\ncrackitt = boolvar(name=\"crackitt\")\ndodgy = boolvar(name=\"dodgy\")\nedgy = boolvar(name=\"edgy\")\nfingers = boolvar(name=\"fingers\")\n\n# At least 4 of them are innocent\nmodel = Model(\n 4 <= sum([~artie, ~bill, ~crackitt, ~dodgy, ~edgy, ~fingers])\n)\n\n# ARTIE: \"It wasn't me.\"\nmodel += [artie == ~artie]\n\n# BILL: \"Crackitt was in it up to his neck.\"\nmodel += [bill == crackitt]\n\n# CRACKITT: \"No I wasn't.\"\nmodel += [crackitt == ~crackitt]\n\n# DODGY: \"If Crackitt did it, Bill did it with him.\"\nmodel += [crackitt <= bill]\n\n# EDGY: \"Nobody did it alone.\"\nmodel += [(~edgy) | (sum([artie, bill, crackitt, dodgy, fingers]) >= 2)]\n\n# FINGERS: \"That\u2019s right: it was Artie and Dodgy together.\"\nmodel += [fingers == (artie & dodgy)]\n\n# Solve the model\nif model.solve():\n solution = {\n \"artie\": artie.value(),\n \"bill\": bill.value(),\n \"crackitt\": crackitt.value(),\n \"dodgy\": dodgy.value(),\n \"edgy\": edgy.value(),\n \"fingers\": fingers.value()\n }\n print(json.dumps(solution))\nelse:\n print(\"No solution found\")"}