id stringlengths 19 55 | category stringclasses 4
values | metadata listlengths 1 4 | description stringlengths 89 2.71k | input_data stringlengths 0 1.5k | model stringlengths 477 7.74k | decision_variables listlengths 1 10 |
|---|---|---|---|---|---|---|
csplib__csplib_001_car_sequencing | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/car_sequencing.ipynb",
"# Source description: https://www.csplib.org/Problems/prob001/"
] | A number of cars are to be produced; they are not identical, because different options are available as variants on the basic model. The assembly line has different stations which install the various options (air-conditioning, sunroof, etc.). These stations have been designed to handle at most a certain percentage of ... | at_most = [1, 2, 2, 2, 1] # The amount of times a property can be present # in a group of consecutive timeslots (see next variable) per_slots = [2, 3, 3, 5, 5] # The amount of consecutive timeslots demand = [1, 1, 2, 2, 2, 2] # The demand per type of car requires = [[1, 0, 1, 1, 0], [0, 0, 0, 1, 0], ... | # Data
at_most = [1, 2, 2, 2, 1] # The amount of times a property can be present
# in a group of consecutive timeslots (see next variable)
per_slots = [2, 3, 3, 5, 5] # The amount of consecutive timeslots
demand = [1, 1, 2, 2, 2, 2] # The demand per type of car
requires = [[1, 0, 1, 1, 0],
[0, 0, 0, 1, 0... | [
"sequence"
] |
csplib__csplib_002_template_design | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob002_template_design.py",
"# Source description: https://www.csplib.org/Problems/prob002/"
] | This problem arises from a colour printing firm which produces a variety of products from thin board, including cartons for human and animal food and magazine inserts. Food products, for example, are often marketed as a basic brand with several variations (typically flavours). Packaging for such variations usually has ... | n_slots = 9 # The amount of slots on a template n_templates = 2 # The amount of templates n_var = 7 # The amount of different variations demand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation | # Data
n_slots = 9 # The amount of slots on a template
n_templates = 2 # The amount of templates
n_var = 7 # The amount of different variations
demand = [250, 255, 260, 500, 500, 800, 1100] # The demand per variation
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
ub = max(demand) #... | [
"production",
"layout"
] |
csplib__csplib_005_autocorrelation | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob005_auto_correlation.py",
"# Source description: https://www.csplib.org/Problems/prob005/"
] | These problems have many practical applications in communications and electrical engineering. The objective is to construct a binary sequence of length n that minimizes the autocorrelations between bits. Each bit in the sequence takes the value +1 or -1. With non-periodic (or open) boundary conditions, the k-th autocor... | n = 10 # Length of the binary sequence | # Data
n = 10 # Length of the binary sequence
# End of data
# Import libraries
from cpmpy import *
import numpy as np
import json
# periodic auto correlation
def PAF(arr, s):
# roll the array 's' indices
return sum(arr * np.roll(arr, -s))
# Decision Variables
sequence = intvar(-1, 1, shape=n, name="sequen... | [
"sequence",
"E"
] |
csplib__csplib_006_golomb_rules | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob006_golomb.py",
"# Source description: https://www.csplib.org/Problems/prob006/"
] | These problems are said to have many practical applications including sensor placements for x-ray crystallography and radio astronomy. A Golomb ruler may be defined as a set of \( m \) integers \( 0 = a_1 < a_2 < \cdots < a_m \) such that the \( \frac{m(m-1)}{2} \) differences \( a_j - a_i, \, 1 \leq i < j \leq m \) ar... | size = 10 # Number of marks on the Golomb ruler | # Data
size = 10 # Number of marks on the Golomb ruler
# End of data
# Import libraries
from cpmpy import *
import json
# Decision variables
marks = intvar(0, size * size, shape=size, name="marks")
length = marks[-1]
# Model
model = Model()
# first mark is 0
model += (marks[0] == 0)
# marks must be increasing
mod... | [
"marks",
"length"
] |
csplib__csplib_007_all_interval | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob007_all_interval.py",
"# Source description: https://www.csplib.org/Problems/prob007/"
] | Given the twelve standard pitch-classes (c, c#, d, β¦), represented by numbers \(0, 1, \ldots, 11\), find a series in which each pitch-class occurs exactly once and in which the musical intervals between neighbouring notes cover the full set of intervals from the minor second (1 semitone) to the major seventh (11 semito... | n = 12 # Number of pitch-classes | # Data
n = 12 # Number of pitch-classes
# End of data
# Import libraries
from cpmpy import *
import numpy as np
import json
# Create the solver
model = Model()
# Declare variables
x = intvar(0, n - 1, shape=n, name="x") # Pitch-classes
diffs = intvar(1, n - 1, shape=n - 1, name="diffs") # Intervals
# Constraints... | [
"diffs",
"x"
] |
csplib__csplib_008_vessel_loading | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob008_vessel_loading.py",
"# Source description: https://www.csplib.org/Problems/prob008/"
] | Supply vessels transport containers from site to site. The deck area is rectangular. Containers are cuboid, and are laid out in a single layer. All containers are positioned parallel to the sides of the deck. The contents of the containers determine their class. Certain classes of containers are constrained to be separ... | deck_width = 5 # Width of the deck deck_length = 5 # Length of the deck n_containers = 3 # Number of containers width = [5, 2, 3] # Widths of containers length = [1, 4, 4] # Lengths of containers classes = [1, 1, 1] # Classes of containers separation = [ # Separation constraints between classes [0, 0], [... | # Data
deck_width = 5 # Width of the deck
deck_length = 5 # Length of the deck
n_containers = 3 # Number of containers
width = [5, 2, 3] # Widths of containers
length = [1, 4, 4] # Lengths of containers
classes = [1, 1, 1] # Classes of containers
separation = [ # Separation constraints between classes
[0, 0]... | [
"right",
"top",
"left",
"bottom"
] |
csplib__csplib_009_perfect_square_placement | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob009_perfect_squares.py",
"# Source description: https://www.csplib.org/Problems/prob009/"
] | The perfect square placement problem (also called the squared square problem) is to pack a set of squares with given integer sizes into a bigger square in such a way that no squares overlap each other and all square borders are parallel to the border of the big square. For a perfect placement problem, all squares have ... | base = 6 # Side length of the large square sides = [3, 3, 3, 2, 1, 1, 1, 1, 1] # Side lengths of the smaller squares | # Data
base = 6 # Side length of the large square
sides = [3, 3, 3, 2, 1, 1, 1, 1, 1] # Side lengths of the smaller squares
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
def perfect_squares(base, sides):
model = Model()
side... | [
"y_coords",
"x_coords"
] |
csplib__csplib_010_social_golfers_problem | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob010_social_golfers.py",
"# Source description: https://www.csplib.org/Problems/prob010/"
] | The coordinator of a local golf club has come to you with the following problem. In their club, there are 32 social golfers, each of whom play golf once a week, and always in groups of 4. They would like you to come up with a schedule of play for these golfers, to last as many weeks as possible, such that no golfer pla... | n_weeks = 4 # Number of weeks n_groups = 3 # Number of groups group_size = 3 # Size of each group | # Data
n_weeks = 4 # Number of weeks
n_groups = 3 # Number of groups
group_size = 3 # Size of each group
# End of data
# Import libraries
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
import numpy as np
import json
def social_golfers(n_weeks, n_groups, group_size):
n_golfers = n_groups * ... | [
"assign"
] |
csplib__csplib_011_acc_basketball_schedule | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob011_basketball_schedule.py",
"# Source description: https://www.csplib.org/Problems/prob011/"
] | The problem is finding a timetable for the 1997/98 Atlantic Coast Conference (ACC) in basketball. It was first tackled by Nemhauser and Trick. The 9 basketball teams in the tournament are Clemson (Clem), Duke (Duke), Florida State (FSU), Georgia Tech (GT), Maryland (UMD), North Carolina (UNC), North Carolina State (NC... | n_teams = 9 n_days = 18 | # Data
n_teams = 9
n_days = 18
# End of data
# Import libraries
from cpmpy import *
import numpy as np
import json
def basketball_schedule():
n_teams = 9
n_days = 18
# Teams
teams = np.arange(n_teams)
CLEM, DUKE, FSU, GT, UMD, UNC, NCSt, UVA, WAKE = teams
rivals = [GT, UNC, FSU, CLEM, UVA, D... | [
"config",
"where"
] |
csplib__csplib_012_nonogram | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob012_nonogram.py",
"# Source description: https://www.csplib.org/Problems/prob012/"
] | Nonograms are a popular puzzle, which goes by different names in different countries. Solvers have to shade in squares in a grid so that blocks of consecutive shaded squares satisfy constraints given for each row and column. Constraints typically indicate the sequence of shaded blocks (e.g. 3,1,2 means that there is a ... | rows = 8 # Number of rows row_rule_len = 2 # Maximum length of row rules row_rules = [ [0, 1], [0, 2], [4, 4], [0, 12], [0, 8], [0, 9], [3, 4], [2, 2] ] # Rules for rows cols = 13 # Number of columns col_rule_len = 2 # Maximum length of column rules col_rules = [ [0, 2], [2,... | # Data
rows = 8 # Number of rows
row_rule_len = 2 # Maximum length of row rules
row_rules = [
[0, 1],
[0, 2],
[4, 4],
[0, 12],
[0, 8],
[0, 9],
[3, 4],
[2, 2]
] # Rules for rows
cols = 13 # Number of columns
col_rule_len = 2 # Maximum length of column rules
col_rules = [
[0, 2],
... | [
"board"
] |
csplib__csplib_013_progressive_party_problem | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob013_progressive_party.py",
"# Source description: https://www.csplib.org/Problems/prob013/"
] | The problem is to timetable a party at a yacht club. Certain boats are to be designated hosts, and the crews of the remaining boats in turn visit the host boats for several successive half-hour periods. The crew of a host boat remains on board to act as hosts while the crew of a guest boat together visits several hosts... | n_boats = 5 # Number of boats n_periods = 4 # Number of periods capacity = [6, 8, 12, 12, 12] # Capacities of the boats crew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats | # Data
n_boats = 5 # Number of boats
n_periods = 4 # Number of periods
capacity = [6, 8, 12, 12, 12] # Capacities of the boats
crew_size = [2, 2, 2, 2, 4] # Crew sizes of the boats
# End of data
# Import libraries
import json
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
def progressive_party... | [
"is_host",
"visits"
] |
csplib__csplib_015_schurs_lemma | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob015_shur_lemma.py",
"# Source description: https://www.csplib.org/Problems/prob015/"
] | The problem is to put \( n \) balls labelled \( 1, \ldots, n \) into 3 boxes so that for any triple of balls \( (x, y, z) \) with \( x + y = z \), not all are in the same box. This has a solution iff \( n < 14 \). The problem can be formulated as a 0-1 problem using the variables \( M_{ij} \) for \( i \in \{1, \ldots, ... | n = 13 # Number of balls c = 3 # Number of boxes | # Data
n = 13 # Number of balls
c = 3 # Number of boxes
# End of data
# Import libraries
import json
from cpmpy import *
def shur_lemma(n, c):
# balls[i] = j iff ball i is in box j
balls = intvar(1, c, shape=n, name="balls")
model = Model()
# Ensure each triple (x, y, z) with x + y = z are not in... | [
"balls"
] |
csplib__csplib_019_magic_squares_and_sequences | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob019_magic_sequence.py",
"# Source description: https://www.csplib.org/Problems/prob019/"
] | An order \( n \) magic square is a \( n \) by \( n \) matrix containing the numbers 1 to \( n^2 \), with each row, column, and main diagonal equal to the same sum. As well as finding magic squares, we are interested in the number of a given size that exist. There are several interesting variations. For example, we may ... | n = 12 # Length of the magic sequence | # Data
n = 12 # Length of the magic sequence
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
def magic_sequence(n):
model = Model()
x = intvar(0, n - 1, shape=n, name="x")
# Constraints
for i in range(n):
model += x[i] == sum(x == i)
# Speedup search... | [
"x"
] |
csplib__csplib_021_crossfigures | csplib | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/crossfigure.py",
"# Source description: https://www.csplib.org/Problems/prob021/",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Crossfigures are the numerical equivalent of crosswords. You have a grid and some clues with numerical answers to place on this grid. Clues come in several different forms (for example: Across 1. 25 across times two, 2. five dozen, 5. a square number, 10. prime, 14. 29 across times 21 down ...). Here is the specific p... | # Import libraries
import math
from cpmpy import *
import json
def member_of(x, val):
"""
member_of(x, val)
Ensures that the value `val` is in the array `x`.
"""
n = len(x)
# cc = intvar(0,n)
# constraints = [count(x, val, cc), cc > 0]
constraints = [sum([x[i] == val for i in range(n... | [
"M"
] | |
csplib__csplib_024_langford | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob024_langford.py",
"# Source description: https://www.csplib.org/Problems/prob024/"
] | Consider two sets of the numbers from 1 to 4. The problem is to arrange the eight numbers in the two sets into a single sequence in which the two 1βs appear one number apart, the two 2βs appear two numbers apart, the two 3βs appear three numbers apart, and the two 4βs appear four numbers apart. The problem generalizes... | k = 4 # Number of sets | # Data
k = 4 # Number of sets
# End of data
# Import libraries
import json
from cpmpy import *
def langford(k):
model = Model()
if not (k % 4 == 0 or k % 4 == 3):
print("There is no solution for K unless K mod 4 == 0 or K mod 4 == 3")
return None, None
# Variables
position = intvar... | [
"position",
"solution"
] |
csplib__csplib_026_sports_tournament_scheduling | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob026_sport_scheduling.py",
"# Source description: https://www.csplib.org/Problems/prob026/"
] | The problem is to schedule a tournament of \( n \) teams over \( n-1 \) weeks, with each week divided into \( n/2 \) periods, and each period divided into two slots. The first team in each slot plays at home, whilst the second plays the first team away. A tournament must satisfy the following three constraints: every t... | n_teams = 8 # Number of teams | # Data
n_teams = 8 # Number of teams
# End of data
# Import libraries
import json
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
import numpy as np
def sport_scheduling(n_teams):
n_weeks, n_periods, n_matches = n_teams - 1, n_teams // 2, (n_teams - 1) * n_teams // 2
home = intvar(1, n_te... | [
"home",
"away"
] |
csplib__csplib_028_bibd | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob028_bibd.py",
"# Source description: https://www.csplib.org/Problems/prob028/"
] | Balanced Incomplete Block Design (BIBD) generation is a standard combinatorial problem from design theory, originally used in the design of statistical experiments but since finding other applications such as cryptography. It is a special case of Block Design, which also includes Latin Square problems. BIBD generation... | v = 9 # Number of distinct objects b = 12 # Number of blocks r = 4 # Number of blocks each object occurs in k = 3 # Number of objects each block contains l = 1 # Number of blocks in which each pair of distinct objects occurs together | # Data
v = 9 # Number of distinct objects
b = 12 # Number of blocks
r = 4 # Number of blocks each object occurs in
k = 3 # Number of objects each block contains
l = 1 # Number of blocks in which each pair of distinct objects occurs together
# End of data
# Import libraries
import json
import numpy as np
from cpmp... | [
"matrix"
] |
csplib__csplib_033_word_design | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob033_word_design.py",
"# Source description: https://www.csplib.org/Problems/prob033/"
] | This problem has its roots in Bioinformatics and Coding Theory. Problem: find as large a set \( S \) of strings (words) of length 8 over the alphabet \( W = \{ A,C,G,T \} \) with the following properties: - Each word in \( S \) has 4 symbols from \{ C,G \}; - Each pair of distinct words in \( S \) differ in at least ... | n = 8 # Number of words to find | # Data
n = 8 # Number of words to find
# End of data
# Import libraries
import json
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
def word_design(n=2):
A, C, G, T = 1, 2, 3, 4
# words[i,j] is the j'th letter of the i'th word
words = intvar(A, T, shape=(n, 8), name="words")
model... | [
"words"
] |
csplib__csplib_044_steiner | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob044_steiner.py",
"# Source description: https://www.csplib.org/Problems/prob044/"
] | The ternary Steiner problem of order \( n \) consists of finding a set of \( n \cdot (n-1)/6 \) triples of distinct integer elements in \(\{1, \ldots, n\}\) such that any two triples have at most one common element. It is a hypergraph problem coming from combinatorial mathematics [luneburg1989tools] where \( n \) modul... | n = 9 # Order of the Steiner Triple System | # Data
n = 9 # Order of the Steiner Triple System
# End of data
# Import libraries
import json
from cpmpy import *
from cpmpy.expressions.utils import all_pairs
def steiner(n=15):
assert n % 6 == 1 or n % 6 == 3, "N must be (1|3) modulo 6"
n_sets = int(n * (n - 1) // 6)
model = Model()
# boolean r... | [
"sets"
] |
csplib__csplib_049_number_partitioning | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob049_number_partitioning.py",
"# Source description: https://www.csplib.org/Problems/prob049/"
] | This problem consists in finding a partition of numbers 1..N into two sets A and B such that: - A and B have the same cardinality - Sum of numbers in A = sum of numbers in B - Sum of squares of numbers in A = sum of squares of numbers in B There is no solution for \( N < 8 \). Here is an example for \( N = 8 \): A =... | n = 12 # The number N | # Data
n = 12 # The number N
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
def number_partitioning(n=8):
assert n % 2 == 0, "The value of n must be even"
# x[i] is the ith value of the first set
x = intvar(1, n, shape=n // 2)
# y[i] is the ith value of the seco... | [
"A",
"B"
] |
csplib__csplib_050_diamond_free | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob050_diamond_free.py",
"# Source description: https://www.csplib.org/Problems/prob050/"
] | Given a simple undirected graph \( G = (V, E) \), where \( V \) is the set of vertices and \( E \) the set of undirected edges, the edge \(\{u, v\}\) is in \( E \) if and only if vertex \( u \) is adjacent to vertex \( v \in G \). The graph is simple in that there are no loop edges, i.e., we have no edges of the form \... | N = 10 # Number of vertices in the graph | # Data
N = 10 # Number of vertices in the graph
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
from itertools import combinations
def diamond_free(N=10):
# By definition a and b will have the same cardinality:
matrix = boolvar(shape=(N, N), name="matrix")
model = Mod... | [
"matrix"
] |
csplib__csplib_053_graceful_graphs | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob053_gracefull_graphs.py",
"# Source description: https://www.csplib.org/Problems/prob053/"
] | A labelling \( f \) of the nodes of a graph with \( q \) edges is graceful if \( f \) assigns each node a unique label from \( \{0, 1, \ldots, q\} \) and when each edge \( xy \) is labelled with \( |f(x) - f(y)| \), the edge labels are all different. Gallian surveys graceful graphs, i.e., graphs with a graceful labelli... | m = 16 # Number of edges in the graph n = 8 # Number of nodes in the graph graph = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3], [4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7], [0, 4], [1, 5], [2, 6], [3, 7]] # Edges of the graph | # Data
m = 16 # Number of edges in the graph
n = 8 # Number of nodes in the graph
graph = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3],
[4, 5], [4, 6], [4, 7], [5, 6], [5, 7], [6, 7],
[0, 4], [1, 5], [2, 6], [3, 7]] # Edges of the graph
# End of data
# Import libraries
import json
from cpmpy im... | [
"edges",
"nodes"
] |
csplib__csplib_054_n_queens | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob054_n_queens.py",
"# Source description: https://www.csplib.org/Problems/prob054/"
] | Can \( n \) queens (of the same color) be placed on a \( n \times n \) chessboard so that none of the queens can attack each other? In chess, a queen attacks other squares on the same row, column, or either diagonal as itself. So the \( n \)-queens problem is to find a set of \( n \) locations on a chessboard, no two o... | n = 10 # Size of the chessboard and number of queens | # Data
n = 10 # Size of the chessboard and number of queens
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
def n_queens(n=8):
queens = intvar(1, n, shape=n, name="queens")
# Constraints on columns and left/right diagonal
model = Model([
AllDifferent(queens),... | [
"queens"
] |
csplib__csplib_076_costas_arrays | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob076_costas_arrays.py",
"# Source description: https://www.csplib.org/Problems/prob076/"
] | A Costas array is a pattern of \( n \) marks on an \( n \times n \) grid, one mark per row and one per column, in which the \( n \cdot (n-1)/2 \) vectors between the marks are all different. Such patterns are important as they provide a template for generating radar and sonar signals with ideal ambiguity functions. A... | n = 8 # Size of the Costas array | # Data
n = 8 # Size of the Costas array
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
def costas_array(n=6):
model = Model()
# Declare variables
costas = intvar(1, n, shape=n, name="costas")
differences = intvar(-n + 1, n - 1, shape=(n, n), name="differences")
... | [
"costas"
] |
csplib__csplib_084_hadamard_matrix | csplib | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/csplib/prob084_hadamard_matrix.py",
"# Source description: https://www.csplib.org/Problems/prob084/"
] | For every odd positive integer \( \ell \) (and \( m = \frac{\ell - 1}{2} \)) we define the 2cc Hadamard matrix Legendre pairs CSP using the \{V, D, C\} format (Variables, Domains, Constraints) as follows: - \( V = \{a_1, \ldots, a_\ell, b_1, \ldots, b_\ell\} \), a set of \( 2 \cdot \ell \) variables - \( D = \{D_{a_1}... | l = 9 # Value of l (must be an odd positive integer) | # Data
l = 9 # Value of l (must be an odd positive integer)
# End of data
# Import libraries
import json
import numpy as np
from cpmpy import *
def PAF(arr, s):
return sum(arr * np.roll(arr,-s))
def hadamard_matrix(l=5):
m = int((l - 1) / 2)
a = intvar(-1,1, shape=l, name="a")
b = intvar(-1,1, sha... | [
"b",
"a"
] |
hakan_examples__abbots_puzzle | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/abbots_puzzle.py"
] | If 100 bushels of corn were distributed among 100 people such that each man received three bushels, each woman two, and each child half a bushel, and there are five times as many women as men, find the number of men, women, and children. Print the number of men, women, and children (men, women, children). | # Import libraries
from cpmpy import *
import json
# Decision variables
men = intvar(0, 100, name="men")
women = intvar(0, 100, name="women")
children = intvar(0, 100, name="children")
# Model
model = Model([
men + women + children == 100, # Total number of people
men * 6 + women * 4 + children == 200, # To... | [
"men",
"women",
"children"
] | |
hakan_examples__added_corners | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/added_corner.py"
] | Enter the digits 1 through 8 in the circles and squares such that the number in each square is equal to the sum of the numbers in the adjoining circles. ... C F C F F C F C ''' Print the values for each position (positions). | # Import libraries
from cpmpy import *
import json
# Parameters
n = 8 # Number of digits
# Decision variables
positions = intvar(1, n, shape=n, name="positions")
a, b, c, d, e, f, g, h = positions
# Model
model = Model([
AllDifferent(positions),
b == a + c,
d == a + f,
e == c + h,
g == f + h
])
... | [
"positions"
] | |
hakan_examples__ages_of_the_sons | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/ages_of_the_sons.py",
"# Source description: http://blog.athico.com/2007/08/drools-puzzle-round-1-ages-of-sons.html"
] | An old man asked a mathematician to guess the ages of his three sons. Old man said: "The product of their ages is 36." Mathematician said: "I need more information." Old man said:"Over there you can see a building. The sum of their ages equals the number of the windows in that building." After a short while the mathe... | # Import libraries
from cpmpy import *
import json
A1 = intvar(0, 36, name="A1") # oldest son
A2 = intvar(0, 36, name="A2")
A3 = intvar(0, 36, name="A3")
B1 = intvar(0, 36, name="B1")
B2 = intvar(0, 36, name="B2")
B3 = intvar(0, 36, name="B3")
AS = intvar(0, 1000, name="AS")
BS = intvar(0, 1000, name="BS")
model =... | [
"A3",
"A1",
"A2"
] | |
hakan_examples__age_changing | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/age_changing.py",
"# Source description: https://enigmaticcode.wordpress.com/2015/06/20/enigma-1224-age-changing/"
] | If you start with my age, in years, and apply the four operations: [ +2 /8 -3 *7 ] in some order, then the final answer you get is my husband's age. Funnily enough, if you start with his age and apply the same four operations in a different order, then you get my age. What are our two ages? Print my age ... | # Import libraries
from cpmpy import *
import json
def check(perm, old, new):
return [
(perm == 0).implies(new == old + 2),
# (perm == 1).implies(new == old / 8), # This give a lot of bad solutions
(perm == 1).implies(8*new == old), # This works
(perm == 2).implies(new == old - ... | [
"m",
"h"
] | |
hakan_examples__allergy | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/allergy.py"
] | Four friends (two women named Debra and Janet, and two men named Hugh and Rick) found that each of them is allergic to something different: eggs, mold, nuts and ragweed. We would like to match each one's surname (Baxter, Lemon, Malone and Fleet) with his or her allergy. We know that: - Rick is not allergic to mold - ... | # Import libraries
from cpmpy import *
import json
n = 4
friends = Debra, Janet, Hugh, Rick = list(range(n))
friends_s = ["Debra", "Janet", "Hugh", "Rick"]
# foods[i] is the friend allergic to the ith food
eggs, mold, nuts, ragweed = foods = intvar(0, n - 1, shape=n, name="foods")
foods_s = ["eggs", "mold", "nuts", "... | [
"malone",
"baxter",
"nuts",
"ragweed",
"mold",
"fleet",
"lemon",
"eggs"
] | |
hakan_examples__among | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/among.py",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Requires exactly m variables in x to take one of the values in v. Print the array x (x). | n = 5 # Length of x m = 3 # Number of values v = [1, 5, 8] # Values to be among in x | # Data
n = 5 # Length of x
m = 3 # Number of values
v = [1, 5, 8] # Values to be among in x
# End of data
# Import libraries
from cpmpy import *
import json
def among(m,x,v):
"""
among(m,x,v)
Requires exactly m variables in x to take one of the values in v.
"""
return [m == sum([x[i] == j for i in rang... | [
"x"
] |
hakan_examples__appointment_scheduling | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/appointment_scheduling.py",
"# Source description: http://stackoverflow.com/questions/11143439/appointment-scheduling-algorithm-n-people-with-n-free-busy-slots-constraint-sa"
] | Schedule 4 people into 4 interview slots based on their free-busy schedules. Print the assignment of people to slots (x) where 1 means the person is assigned to the slot and 0 means the person is not assigned to the slot. | m = [ [1, 1, 1, 1], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1] ] # Matrix representing the free-busy schedules | # Data
m = [
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1]
] # Matrix representing the free-busy schedules
# End of data
# Import libraries
from cpmpy import *
import json
import random
model = Model()
n = len(m)
# decision variables
# the assignment of persons to a slot (appointment numb... | [
"x"
] |
hakan_examples__archery_puzzle | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/archery_puzzle.py"
] | How close can the young archer come to scoring a total of 100 using as many arrows as she pleases? The targets are: 16, 17, 23, 24, 39, 40. Print the number of hits on each target (hits). | # Import libraries
from cpmpy import *
import json
# Parameters
targets = [16, 17, 23, 24, 39, 40]
n = len(targets)
target_score = 100
# Decision variables
hits = intvar(0, 100, shape=n, name="hits")
score = intvar(0, 100, name="score")
deviation = intvar(0, 100, name="deviation")
# Model
model = Model([
score =... | [
"hits"
] | |
hakan_examples__arch_friends | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/arch_friends.py"
] | Harriet, upon returning from the mall, is happily describing her four shoe purchases to her friend Aurora. Aurora just loves the four different kinds of shoes that Harriet bought (ecru espadrilles, fuchsia flats, purple pumps, and suede sandals), but Harriet can't recall at which different store (Foot Farm, Heels i... | # Import libraries
from cpmpy import *
import numpy as np
import json
n = 4
model = Model()
shoes = intvar(1, n, shape=n, name="shoes")
ecruespadrilles, fuchsiaflats, purplepumps, suedesandals = shoes
store = intvar(1, n, shape=n, name="store")
footfarm, heelsinahandcart, theshoepalace, tootsies = store
model += [... | [
"ecruespadrilles",
"purplepumps",
"theshoepalace",
"suedesandals",
"footfarm",
"fuchsiaflats",
"tootsies",
"heelsinahandcart"
] | |
hakan_examples__assignment_costs | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/assignment.py",
"# Source description: Winston 'Operations Research', Assignment Problems, page 393f"
] | Assign people to 4 tasks with different costs, so that the total cost is minimized. Each task must be assigned to exactly one person, but it is not necessary to assign all people to a task. Print whether each task is assigned to a person (x), where 1 means the task is assigned to the person and 0 means the task is not... | cost = [ # Cost matrix, rows are tasks, columns are people [14, 5, 8, 7, 15], [2, 12, 6, 5, 3], [7, 8, 3, 9, 7], [2, 4, 6, 10, 1] ] # Cost matrix | # Data
cost = [ # Cost matrix, rows are tasks, columns are people
[14, 5, 8, 7, 15],
[2, 12, 6, 5, 3],
[7, 8, 3, 9, 7],
[2, 4, 6, 10, 1]
] # Cost matrix
# End of data
# Import libraries
from cpmpy import *
import numpy as np
import json
# Parameters
rows = len(cost)
cols = len(cost[0])
# Decision v... | [
"x"
] |
hakan_examples__autoref | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/autoref.py",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Given an integer n > 0 and an integer m >= 0, find a non-empty finite series S=(s0, s1, ..., sn, sn+1) such that ( 1) there are si occurrences of i in S for each integer i ranging from 0 to n, and (2) sn+1=m. Print the series S (s). | n = 27 m = 5 | # Data
n = 27
m = 5
# End of data
# Import libraries
from cpmpy import *
import json
def count(a, val, c):
"""
count(a,val,c)
c is the number of occurrences of val in array a.
"""
return [c == sum([a[i] == val for i in range(len(a))])]
def global_cardinality_count(a, gcc):
"""
global_c... | [
"s"
] |
hakan_examples__bales_of_hay | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/bales_of_hay.py",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | You have five bales of hay. For some reason, instead of being weighed individually, they were weighed in all possible combinations of two. The weights of each of these combinations were written down and arranged in numerical order, without keeping track of which weight matched which pair of bales. The weights, in kilo... | # Import libraries
from cpmpy import *
import json
# Parameters
n = 5
weights = [80, 82, 83, 84, 85, 86, 87, 88, 90, 91]
# variables
bales = intvar(0, 50, shape=n, name="bales")
model = Model()
def increasing(args):
"""
Ensure that the values in args are increasing.
"""
return [args[i - 1] <= args[... | [
"bales"
] | |
hakan_examples__bananas | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/bananas.py"
] | In three dollars, you get 5 bananas, in five dollars, 7 oranges, in seven dollars, 9 mangoes and in nine dollars, three apples, I need to purchase 100 fruits in 100 dollars. Please keep in mind that all type of fruits need to be purchased but I do not like banana and apple, so these should be of minimum quantity. Prin... | # Import libraries
from cpmpy import *
import json
x = intvar(1, 100, shape=4, name="x")
bananas, oranges, mangoes, apples = x
the_sum = intvar(1, 2000, name="the_sum")
model = Model([the_sum == bananas + apples,
# This don't work since "/" does integer division
# 3*bananas/5 + 5*orange... | [
"oranges",
"bananas",
"apples",
"mangoes"
] | |
hakan_examples__best_host | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/best_host.py",
"# Source description: http://www.informs.org/ORMS-Today/Public-Articles/February-Volume-38-Number-1/THE-PUZZLOR",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Hosting a dinner party requires several skills to pull off a successful evening. One of your duties, aside from preparing dinner and selecting the drinks, is to make sure your guests enjoy themselves. Figure 1 shows a dinner table with six seats for your guests. Some guests, however, do not get along with each other. ... | # Import libraries
from cpmpy import *
import json
def member_of(x, val):
"""
member_of(x, val)
Ensures that the value `val` is in the array `x`.
"""
n = len(x)
# cc = intvar(0,n)
# constraints = [count(x, val, cc), cc > 0]
constraints = [sum([x[i] == val for i in range(n)]) > 0]
... | [
"x"
] | |
hakan_examples__big_bang2 | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/big_bang2.py",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Nontransitive dice a la The Big Bang Theory in Comet Thore Graepel (thoregraepel@googlemail.com) The idea is to create a set of five dice such that the dominance relationships between the dice is isomorphic to the corresponding relationships in the game Rock-Paper-Scissors extended by the choices Lizard and Spock. (or... | # Import libraries
from cpmpy import *
import json
def increasing(args):
"""
Ensure that the values in args are increasing.
"""
return [args[i - 1] <= args[i] for i in range(1, len(args))]
rock = 0
paper = 1
scissors = 2
lizard = 3
spock = 4
m = 5 # number of dice
n = 8 # number of faces of each ... | [
"dice"
] | |
hakan_examples__bin_packing | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/bin_packing.py"
] | Given several items of specific weights and a number of bins of a fixed capacity, assign each item to a bin so that the total weight of the items in each bin does not exceed the capacity. Print the bin each item is assigned to (bins) as a list of numbers. | weights = [4, 3, 1, 3, 2, 5, 2] capacity = 5 num_bins = 5 | # Data
weights = [4, 3, 1, 3, 2, 5, 2]
capacity = 5
num_bins = 5
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
n = len(weights)
# Decision variables
bins = intvar(0, num_bins - 1, shape=n, name="bins") # Which bin each item is assigned to
# Model
model = Model([
[sum(weights[j] ... | [
"bins"
] |
hakan_examples__birthday_coins | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/birthday_coins.py",
"# Source description: https://matmod.ch/lpl/PDF//math10.pdf"
] | Tommy was given 15 coins for his birthday (half-crowns, shillings and sixpence). When he added it up, he found that he had Β£1. 5s. 6d (one pound 5 shillings and 6 pences, see below). How many half-crowns was he given? (This puzzle involve coins from the old British currency. A pound is 20 shillings and a shilling is 1... | # Import libraries
from cpmpy import *
import json
# Parameters
coin_types = 3
values = [30, 12, 6] # Values in pence for half-crowns, shillings, and sixpences
total_value = 240 + 5 * 12 + 6 # Total value in pence
total_coins = 15 # Total number of coins
# Decision variables
coins = intvar(1, 15, shape=coin_types,... | [
"half_crowns"
] | |
hakan_examples__bowls_and_oranges | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/bowls_and_oranges.py",
"# Source description: http://surana.wordpress.com/2011/06/01/constraint-programming-example/",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | You have 40 bowls, all placed in a line at exact intervals of 1 meter. You also have 9 oranges. You wish to place all the oranges in the bowls, no more than one orange in each bowl, so that there are no three oranges A, B, and C such that the distance between A and B is equal to the distance between B and C. Print a s... | # Import libraries
from cpmpy import *
import json
# Parameters
n = 40 # Number of bowls
m = 9 # Number of oranges
# Decision variables
x = intvar(1, n, shape=m, name="x")
def increasing(args):
"""
Ensure that the values in args are increasing.
"""
return [args[i - 1] <= args[i] for i in range(1, ... | [
"x"
] | |
hakan_examples__broken_weights | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/broken_weights.py",
"# Source description: http://www.mathlesstraveled.com/?p=701",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Here's a fantastic problem I recently heard. Apparently it was first posed by Claude Gaspard Bachet de Meziriac in a book of arithmetic problems published in 1612, and can also be found in Heinrich Dorrie's 100 Great Problems of Elementary Mathematics. A merchant had a forty pound measuring weight that broke into ... | # Import libraries
from cpmpy import *
import json
def increasing_strict(args):
"""
Ensure that the values in args are strict increasing.
"""
return [args[i - 1] < args[i] for i in range(1, len(args))]
# Parameters
m = 40
n = 4
# variables
weights = intvar(1, m, shape=n, name="weights")
x = intvar(... | [
"weights"
] | |
hakan_examples__building_blocks | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/building_blocks.py",
"# Source description: http://brownbuffalo.sourceforge.net/BuildingBlocksClues.html",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Each of four alphabet blocks has a single letter of the alphabet on each of its six sides. In all, the four blocks contain every letter but Q and Z. By arranging the blocks in various ways, you can spell all of the words listed below. Can you figure out how the letters are arranged on the four blocks? BAKE ONYX ECHO ... | # Import libraries
from cpmpy import *
import json
import numpy as np
def count(a, val, c):
"""
count(a,val,c)
c is the number of occurrences of val in array a.
"""
return [c == sum([a[i] == val for i in range(len(a))])]
def global_cardinality_count(a, gcc):
"""
global_cardinality_count... | [
"dice"
] | |
hakan_examples__cabling | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/cabling.py",
"# Source description: https://yurichev.com/blog/cabling_Z3/",
"# Misc: http://www.hakank.org/cpmpy/cpmpy_hakank.py"
] | Take a rack cabinet, like this one: [ an image ] Let's say, there are 8 1U devices, maybe servers, routers and whatnot, named as A, B, C, D, E, F, G, H. Devices must be connected by cables: probably twisted pair or whatever network engineers using today. Some devices must be connected by several cables (2 cables, 3 ... | # Import libraries
from cpmpy import *
import json
# Parameters
n = 8
model = Model()
# A <--- 1 cable ---> H
# A <--- 2 cables ---> E
# B <--- 4 cables ---> F
# C <--- 1 cable ---> G
# C <--- 1 cable ---> D
# C <--- 1 cable ---> E
# D <--- 3 cables ---> H
# G <--- 1 cable ---> H
A, B, C, D, E, F, G, H = list(r... | [
"final_sum"
] | |
hakan_examples__calvin_puzzle | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/calvin_puzzle.py",
"# Source description: From 'An Exercise for the Mind: A 10 by 10 Math Puzzle: A Pattern Recognition Game: Meditation on an Open Maze', http://www.chycho.com/?q=Puzzle"
] | The Purpose of the Game To take an n by n grid, representing n^2 squares, and completely fill every square based on two types of movements. Movement Type I) If the next number in the sequence is going to be placed vertically or horizontally, then it must be placed exactly three squares away from the previous number ... | n = 5 | # Data
n = 5
# End of data
# Import libraries
from cpmpy import *
import json
# Decision variables
x = intvar(1, n * n, shape=(n, n), name="x")
x_flat = [x[i, j] for i in range(n) for j in range(n)]
model = Model(AllDifferent(x_flat))
model += (x[0, 0] == 1)
for k in range(1, n * n):
i = intvar(0, n - 1, name=... | [
"x"
] |
hakan_examples__candies | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/candies.py"
] | Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each child.Children get jealous of their immediate neighbors, so if two ... | ratings = [2, 3, 4, 4, 4, 2, 1, 3, 4] # Ratings of the children | # Data
ratings = [2, 3, 4, 4, 4, 2, 1, 3, 4] # Ratings of the children
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
n = len(ratings)
# variables
x = intvar(1, n, shape=n, name="x") # number of candies for each child
z = intvar(1, n * n, name="z") # total number of candies
# const... | [
"z"
] |
hakan_examples__capital_budget | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/capital_budget.py",
"# Source description: Winston 'Operations Research', page 478: Capital budgeting"
] | Stockco is considering four investments. Investment 1 will yield a net present value (NPV) of $16,000; investment 2, an NPV of $22,000; investment 3, an NPV of $12,000; and investment 4, an NPV of $8,000. Each investment requires a certain cash outflow at the present time: investment 1, $5,000; investment 2, $7,000; in... | # Import libraries
from cpmpy import *
import json
# Parameters
budget = 14
npv = [16, 22, 12, 8]
cash_flow = [5, 7, 4, 3]
n = 4
# variables
x = boolvar(shape=n, name="x") # x[i] = 1 if investments i
z = intvar(0, 1000, name="z") # total NPV
# constraints
model = Model([
# the sum of all choosen investments mu... | [
"x"
] | |
hakan_examples__chess_set | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/chess_set.py",
"# Source description: Applications of Optimization with XPress-MP.pdf page 11. The problem is presented on page 7."
] | A small joinery makes two different sizes of boxwood chess sets. The small set requires 3 hours of machining on a lathe, and the large set requires 2 hours. There are four lathes with skilled operators who each work a 40 hour week, so we have 160 lathe-hours per week. The small chess set requires 1 kg of boxwood, and t... | # Import libraries
from cpmpy import *
import json
# Decision variables
small_set = intvar(0, 100, name="small_set")
large_set = intvar(0, 100, name="large_set")
max_profit = intvar(0, 10000, name="max_profit")
# Model
model = Model([
small_set + 3 * large_set <= 200, # Boxwood constraint
3 * small_set + 2 *... | [
"large_set",
"small_set",
"max_profit"
] | |
hakan_examples__circling_squares | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/circling_squares.py",
"# Source description: From the Oz examples http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/circlingsquares.html from 'Amusements in Mathematics, Dudeney', number 43."
] | Circling the squares: The puzzle is to place a different number in each of the ten squares so that the sum of the squares of any two adjacent numbers shall be equal to the sum of the squares of the two numbers diametrically opposite to them. The four numbers placed, as examples, must stand as they are. The square of 1... | # Import libraries
from cpmpy import *
import json
def s(x1, x2, y1, y2):
return x1 * x1 + x2 * x2 == y1 * y1 + y2 * y2
n = 10
# variables
x = intvar(1, 99, shape=n, name="x")
A, B, C, D, E, F, G, H, I, K = x
# constraints
model = Model([AllDifferent(x),
A == 16,
B == 2,
... | [
"H",
"D",
"K",
"G",
"E",
"C",
"I",
"F",
"A",
"B"
] | |
hakan_examples__circular_table_averbach_1_2 | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/averbach_1_2.py"
] | Three players (X, Y, Z) of different nationalities (American, English, French) are seated around a circular table playing a game of Hearts. Each passed three cards to the person on their right. Y passed three hearts to the American, X passed the queen of spades and two diamonds to the person who passed their cards to t... | # Import libraries
from cpmpy import *
import json
# a is right to b
def right_to(a, b):
# return ((a == b+1) | (a == b-2) )
return (a == (b + 1) % 3)
# a is left to b
def left_to(a, b):
return [right_to(b, a)]
n = 3
# variables
players = intvar(0, 2, shape=n, name="players")
x, y, z = players
natio... | [
"y",
"english",
"american",
"french",
"x",
"z"
] | |
hakan_examples__clock_triplets | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/clock_triplets.py",
"# Source description: http://www.f1compiler.com/samples/Dean%20Clark%27s%20Problem.f1.html"
] | Rearrange the numbers on the face of a clock (1 to 12) so no triplet of adjacent numbers has a sum higher than 21. This is the smallest value that the highest sum of a triplet can have. Print the arrangement of the 12 numbers on the clock (x) as a list, with the first number being 12. | # Import libraries
from cpmpy import *
import json
# Parameters
n = 12
# variables
x = intvar(1, n, shape=n, name="x") # The numbers on the clock
triplet_sum = intvar(0, 21, name="triplet_sum")
# constraints
model = Model([AllDifferent(x),
x[0] == 12,
x[1] > x[11],
[(x[i... | [
"x"
] | |
hakan_examples__cmo_2012 | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/2012_CMO_problem.py"
] | Given two positive integers a and b, where a - b is a prime number and a Γ b is a perfect square n^2, find the smallest value of a no less than 2012. Print the values of a, b, n, and p (a, b, n, p). | # Import libraries
from cpmpy import *
import json
from math import sqrt
def is_prime(n):
"""Return True if n is prime, False otherwise"""
if n < 2:
return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
def primes(n):
"""Return a li... | [
"b",
"p",
"a",
"n"
] | |
hakan_examples__coin3_application | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/coins3.py",
"# Source description: From 'Constraint Logic Programming using ECLiPSe' pages 99f and 234 ff. The solution in ECLiPSe is at page 236."
] | Find the minimum number of coins that allows one to pay exactly any amount smaller than one Euro using the denominations 1, 2, 5, 10, 20, 50 cents. Print the number of each type of coin used (x) as a list. | # Import libraries
from cpmpy import *
import json
# Parameters
denominations = [1, 2, 5, 10, 20, 50] # Euro cent denominations
n = len(denominations)
# declare variables
x = intvar(0, 99, shape=n, name="x") # The number of each type of coin used
num_coins = intvar(0, 99, name="num_coins") # The total number of co... | [
"x"
] | |
hakan_examples__coins_grid | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/coins_grid.py",
"# Source description: Tony Hurlimann: \"A coin puzzle - SVOR-contest 2007\" http://www.svor.ch/competitions/competition2007/AsroContestSolution.pdf"
] | In a quadratic grid (or a larger chessboard) with 31x31 cells, one should place coins in such a way that the following conditions are fulfilled: 1. In each row exactly 14 coins must be placed. 2. In each column exactly 14 coins must be placed. 3. The sum of the quadratic horizontal distance from the main ... | # Import libraries
from cpmpy import *
import json
import numpy as np
# Parameters
n = 31
c = 14
# variables
x = intvar(0, 1, shape=(n, n), name="x") # The coins on the grid (1 if a coin is placed, 0 otherwise)
z = intvar(0, 1000000, name="z") # The sum of the quadratic horizontal distance from the main diagonal
m... | [
"x",
"z"
] | |
hakan_examples__contracting_costs | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/contracting_costs.py",
"# Source description: http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/index.html Contracting Costs from 'Mathematical Puzzles of Sam Loyd, Volume 2', number 20."
] | A contractor planning the construction of a house found that he would have to pay: * $ 1,100 to the paper hanger and the painter, * $ 1,700 to the painter and plumber, * $ 1,100 to the plumber and electrician, * $ 3,300 to the electrician and carpenter, * $ 5,300 to the carpenter and mason, * $ 3,200 to th... | # Import libraries
from cpmpy import *
import json
n = 6
x = intvar(1, 5300, shape=n, name="x")
paper_hanger, painter, plumber, electrician, carpenter, mason = x
costs = [[paper_hanger, painter, 1100],
[painter, plumber, 1700],
[plumber, electrician, 1100],
[electrician, carpenter, 3300],
... | [
"painter",
"plumber",
"electrician",
"carpenter",
"mason",
"paper_hanger"
] | |
hakan_examples__covering_opl | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/covering_opl.py",
"# Source description: This example is from the OPL example covering.mod"
] | Select a set of workers to perform all the tasks, while minimizing the cost. Each worker can perform certain tasks and has a hiring cost. Ensure that all tasks are performed. Print the total cost (total_cost) and whether each worker is selected (workers) as a list of 0/1 values. | nb_workers = 32 # Number of workers num_tasks = 15 # Number of tasks Qualified = [ # Which worker is qualified for each task (1-based indexing) [1, 9, 19, 22, 25, 28, 31], [2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32], [3, 10, 19, 24, 26, 30, 32], [4, 21, 25, 28, 32], [5, 11, 16, 22, 23, 27, 31], [6, 2... | # Data
nb_workers = 32 # Number of workers
num_tasks = 15 # Number of tasks
Qualified = [ # Which worker is qualified for each task (1-based indexing)
[1, 9, 19, 22, 25, 28, 31],
[2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32],
[3, 10, 19, 24, 26, 30, 32], [4, 21, 25, 28, 32],
[5, 11, 16, 22, 23, 27, 31]... | [
"total_cost",
"workers"
] |
hakan_examples__crew | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/crew.py",
"# Source description: From Gecode example crew, examples/crew.cc"
] | Assign 20 flight attendants to 10 flights. Each flight needs a certain number of cabin crew, and they have to speak certain languages. Every cabin crew member has two flights off after an attended flight. Print whether each person is assigned to a flight (crew) as a list of lists of 0/1 values. | attributes = [ # steward, hostess, french, spanish, german [1, 0, 0, 0, 1], # Tom = 1 [1, 0, 0, 0, 0], # David = 2 [1, 0, 0, 0, 1], # Jeremy = 3 [1, 0, 0, 0, 0], # Ron = 4 [1, 0, 0, 1, 0], # Joe = 5 [1, 0, 1, 1, 0], # Bill = 6 [1, 0, 0, 1, 0], # Fred = 7 ... | # Data
attributes = [
# steward, hostess, french, spanish, german
[1, 0, 0, 0, 1], # Tom = 1
[1, 0, 0, 0, 0], # David = 2
[1, 0, 0, 0, 1], # Jeremy = 3
[1, 0, 0, 0, 0], # Ron = 4
[1, 0, 0, 1, 0], # Joe = 5
[1, 0, 1, 1, 0], # Bill = 6
[1, 0, 0, 1, 0], # Fred =... | [
"crew"
] |
hakan_examples__crossword | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/crossword2.py",
"# Source description: http://www.cis.temple.edu/~ingargio/cis587/readings/constraints.html"
] | We are to complete the puzzle 1 2 3 4 5 +---+---+---+---+---+ Given the list of words: 1 | 1 | | 2 | | 3 | AFT LASER +---+---+---+---+---+ ALE LEE 2 | # | # | | # | | EEL LINE +---+---+---+---+---+ HEEL SAILS 3 | # | ... | # Import libraries
from cpmpy import *
import json
a = 1;
b = 2;
c = 3;
d = 4;
e = 5;
f = 6;
g = 7;
h = 8;
i = 9;
j = 10;
k = 11;
l = 12;
m = 13;
n = 14;
o = 15;
p = 16;
q = 17;
r = 18;
s = 19;
t = 20;
u = 21;
v = 22;
w = 23;
x = 24;
y = 25;
z = 26;
AA = [
[h, o, s, e, s], # HOSES
[l, a, s, e, r], # LASER
... | [
"E"
] | |
hakan_examples__crypta | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/crypta.py",
"# Source description: Name: crypta.pl, Title: crypt-arithmetic, Original Source: P. Van Hentenryck's book, Adapted by: Daniel Diaz - INRIA France, Date: September 1992"
] | Cryptarithmetic puzzle, solve the operation: B A I J J A J I I A H F C F E B B J E A + D H F G A B C D I D B I F F A G F E J E ----------------------------------------- = G J E G A C D D H F A F J B F I H E E F where all letters are distinct digits. Print the number of each letter (A, B, C, D, E, F, G... | # Import libraries
from cpmpy import *
import json
model = Model()
# variables
LD = intvar(0, 9, shape=10, name="LD")
A, B, C, D, E, F, G, H, I, J = LD
Sr1 = intvar(0, 1, name="Sr1")
Sr2 = intvar(0, 1, name="Sr2")
#
# constraints
#
model += [AllDifferent(LD)]
model += [B >= 1]
model += [D >= 1]
model += [G >= 1]
m... | [
"H",
"D",
"J",
"G",
"E",
"C",
"I",
"F",
"A",
"B"
] | |
hakan_examples__eighteen_hole_golf | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/18_hole_golf.py"
] | Generate a random 18-hole golf course where each hole has a length of 3, 4, or 5, and the total length of the course is 72. Print the lengths of the holes (holes). | # Import libraries
from cpmpy import *
import json
# Parameters
num_holes = 18 # Number of holes
total_length = 72 # Total length of the course
hole_lengths = [3, 4, 5] # Possible lengths for each hole
# Decision variables
holes = intvar(3, 5, shape=num_holes, name="holes") # Lengths of the holes
# Model
model =... | [
"holes"
] | |
hakan_examples__facility_location | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/facility_location_problem.py"
] | A company is considering opening warehouses in four cities to meet regional demands at minimal costs. The potential cities for these warehouses are New York, Los Angeles, Chicago, and Atlanta. The company needs to decide which warehouses to open based on several constraints: 1. If the New York warehouse is opened, the... | warehouse_s = ["New York", "Los Angeles", "Chicago", "Atlanta"] fixed_costs = [400, 500, 300, 150] # Weekly fixed costs per warehouse max_shipping = 100 # Max units per week per warehouse demands = [80, 70, 40] # Weekly demands for regions 1 to 3 shipping_costs = [ [20, 40, 50], # New York to regions 1, 2, 3 ... | # Data
warehouse_s = ["New York", "Los Angeles", "Chicago", "Atlanta"]
fixed_costs = [400, 500, 300, 150] # Weekly fixed costs per warehouse
max_shipping = 100 # Max units per week per warehouse
demands = [80, 70, 40] # Weekly demands for regions 1 to 3
shipping_costs = [
[20, 40, 50], # New York to regions 1, ... | [
"total_cost",
"ships",
"open_warehouse"
] |
hakan_examples__fifty_puzzle | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/50_puzzle.py",
"# Source description: http://www.chlond.demon.co.uk/puzzles/puzzles1.html, puzzle nr. 5."
] | A side show at Coney Island is described as follows: "There were ten little dummies which you were to knock over with baseballs. The man said: 'Take as many throws as you like at a cent apiece and stand as close as you please. Add up the numbers on all the men that you knock down and when the sum amounts to exactly fif... | # Import libraries
from cpmpy import *
import json
# Parameters
target_sum = 50 # Target sum to achieve
values = [15, 9, 30, 21, 19, 3, 12, 6, 25, 27] # Numbers on the dummies
n = len(values)
# Decision variables
dummies = boolvar(shape=n, name="dummies") # Boolean array to indicate which dummies are knocked over
... | [
"dummies"
] | |
hakan_examples__three_coins | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/3_coins.py"
] | Three coins lie on a table in the order tails, heads ,tails. In precisely three moves make them face either all heads or all tails. Print the steps (steps) to make all coins face either all heads or all tails. | num_moves = 3 # Number of moves to make all coins face either all heads or all tails init = [1, 0, 1] # Initial configuration of the coins | # Data
num_moves = 3 # Number of moves to make all coins face either all heads or all tails
init = [1, 0, 1] # Initial configuration of the coins
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
n = len(init)
# decision variables
# 0: heads, 1: tails
steps = boolvar(shape=(num_moves + ... | [
"steps"
] |
hakan_examples__three_sum | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/3sum.py"
] | Given a collection of integers, find three elements that sum to zero. Print whether each element is selected (indices). | nums = [-1, 6, 8, 9, 10, -100, 78, 0, 1] # Collection of integers | # Data
nums = [-1, 6, 8, 9, 10, -100, 78, 0, 1] # Collection of integers
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
n = len(nums)
m = 3 # The number of elements that should sum to 0
# Decision variables
indices = boolvar(shape=n, name="indices") # Boolean array to indicate which... | [
"indices"
] |
hakan_examples__twelve_pack | hakan_examples | [
"#!/usr/bin/python3",
"# Source: http://www.hakank.org/cpmpy/12_pack_problem.py"
] | Given a target number of beers, find the closest combination of 7-packs and 13-packs that meets or exceeds the target. Print the counts of 7-packs and 13-packs used (counts). | target = 20 # Target number of beers | # Data
target = 20 # Target number of beers
# End of data
# Import libraries
from cpmpy import *
import json
import builtins
# Parameters
n = 2 # Number of pack sizes
packs = [7, 13] # Pack sizes
max_val = target * 2 # Arbitrary max limit of pack counts
# Decision variables
counts = intvar(0, max_val, shape=n, n... | [
"counts"
] |
cpmpy_examples__bus_scheduling | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/bus_schedule.py",
"# Source description: Problem from Taha \"Introduction to Operations Research\", page 58."
] | Progress City is considering a mass-transit bus system to reduce in-city driving. The goal is to determine the minimum number of buses required to meet the transportation needs throughout the day. The demand for buses is approximated as constant over successive 4-hour intervals. Each bus can operate only 8 successive h... | demands = [4, 8, 10, 7, 12, 4] # Demand for buses in each 4-hour time slot | # Data
demands = [4, 8, 10, 7, 12, 4] # Demand for buses in each 4-hour time slot
# End of data
# Import libraries
from cpmpy import *
import json
# Parameters
slots = len(demands)
# Decision Variables
# x[i] represents the number of buses scheduled to start working in the i-th 4-hour slot
x = intvar(0, sum(demands... | [
"x"
] |
cpmpy_examples__jobshop | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/jobshop.py",
"# Source description: https://developers.google.com/optimization/scheduling/job_shop"
] | Job Shop Scheduling Problem One common scheduling problem is the job shop, in which multiple jobs are processed on several machines. Each job consists of a sequence of tasks, which must be performed in a given order, and each task must be processed on a specific machine. For example, the job could be the manufacture ... | jobs_data = [ # (job_id, task_id) -> (machine_id, duration) [(0, 3), (1, 2), (2, 2)], # Job 0 [(0, 2), (2, 1), (1, 4)], # Job 1 [(1, 4), (2, 3)] # Job 2 ] | # Data
jobs_data = [ # (job_id, task_id) -> (machine_id, duration)
[(0, 3), (1, 2), (2, 2)], # Job 0
[(0, 2), (2, 1), (1, 4)], # Job 1
[(1, 4), (2, 3)] # Job 2
]
# End of data
# Import libraries
from cpmpy import *
import json
from itertools import combinations
import builtins # To access the... | [
"makespan"
] |
cpmpy_examples__knapsack | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/knapsack.py"
] | A hiker is planning a trip and needs to decide which items to take in their backpack. Each item has a certain value and weight, and the hiker wants to maximize the total value of the items in the backpack without exceeding the weight capacity of the backpack. Print which items to take (x). | values = [4, 2, 3, 7, 1] # Values of the items weights = [3, 1, 2, 5, 4] # Weights of the items capacity = 7 # Capacity of the knapsack | # Data
values = [4, 2, 3, 7, 1] # Values of the items
weights = [3, 1, 2, 5, 4] # Weights of the items
capacity = 7 # Capacity of the knapsack
# End of data
# Import libraries
from cpmpy import *
import json
# Construct the model
x = boolvar(shape=len(values), name="x")
model = Model(
sum(x * weights) <= capa... | [
"x"
] |
cpmpy_examples__mario | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/mario.py"
] | Mario Problem Mario needs to collect as much gold as possible by visiting different houses. He starts at Mario's house and ends at Luigi's house. Each house has a certain amount of gold and the travel between houses consumes fuel. Mario has a limited amount of fuel, and he needs to plan his route to maximize the gold ... | data = { 'nbHouses': 15, 'MarioHouse': 1, 'LuigiHouse': 2, 'fuelMax': 2000, 'goldTotalAmount': 1500, 'conso': [ # fuel consumption between houses, conso[i][j] = fuel from i to j [0, 221, 274, 808, 13, 677, 670, 921, 943, 969, 13, 18, 217, 86, 322], [0, 0, 702, 83, 813, 679, 906,... | # Data
data = {
'nbHouses': 15,
'MarioHouse': 1,
'LuigiHouse': 2,
'fuelMax': 2000,
'goldTotalAmount': 1500,
'conso': [ # fuel consumption between houses, conso[i][j] = fuel from i to j
[0, 221, 274, 808, 13, 677, 670, 921, 943, 969, 13, 18, 217, 86, 322],
[0, 0, 702, 83, 813, 67... | [
"s"
] |
cpmpy_examples__minesweeper | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/minesweeper.py",
"# Source description: https://minesweeper.online"
] | Minesweeper rules are very simple. The board is divided into cells, with mines randomly distributed. To win, you need to open all the cells. The number on a cell shows the number of mines adjacent to it. Using this information, you can determine cells that are safe, and cells that contain mines. Cells suspected of bein... | X = -1 game_data = [ # 0-8: number of mines around, -1: not opened [2, 3, X, 2, 2, X, 2, 1], [X, X, 4, X, X, 4, X, 2], [X, X, X, X, X, X, 4, X], [X, 5, X, 6, X, X, X, 2], [2, X, X, X, 5, 5, X, 2], [1, 3, 4, X, X, X, 4, X], [0, 1, X, 4, X, X, X, 3], [0, 1, 2, X, 2, 3, X, 2] ] | # Data
X = -1
game_data = [ # 0-8: number of mines around, -1: not opened
[2, 3, X, 2, 2, X, 2, 1],
[X, X, 4, X, X, 4, X, 2],
[X, X, X, X, X, X, 4, X],
[X, 5, X, 6, X, X, X, 2],
[2, X, X, X, 5, 5, X, 2],
[1, 3, 4, X, X, X, 4, X],
[0, 1, X, 4, X, X, X, 3],
[0, 1, 2, X, 2, 3, X, 2]
]
# En... | [
"mines"
] |
cpmpy_examples__n_puzzle | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/npuzzle.py"
] | N-Puzzle Problem The N-Puzzle is a classic sliding puzzle game where the goal is to move tiles on a grid to achieve a specific end configuration. The puzzle consists of a grid with \( n+1 \) tiles, one of which is empty. The objective is to trace the steps to the original picture by moving the tiles into their correct... | N = 20 # Number of steps to the solution puzzle_start = [ # Start state of the puzzle, 0 represents the empty tile [0, 3, 6], [2, 4, 8], [1, 7, 5] ] puzzle_end = [ # End state of the puzzle [1, 2, 3], [4, 5, 6], [7, 8, 0] ] | # Data
N = 20 # Number of steps to the solution
puzzle_start = [ # Start state of the puzzle, 0 represents the empty tile
[0, 3, 6],
[2, 4, 8],
[1, 7, 5]
]
puzzle_end = [ # End state of the puzzle
[1, 2, 3],
[4, 5, 6],
[7, 8, 0]
]
# End of data
# Import libraries
from cpmpy import *
import ... | [
"steps"
] |
cpmpy_examples__packing_rectangles | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/packing_rectangles.ipynb",
"# Source Description: https://github.com/Alexander-Schiendorfer/cp-examples/tree/main/packing"
] | The rectangular packing problem involves placing a set of rectangular items into a larger rectangular area such that no items overlap and all items are within the boundaries of the larger area. The objective is to minimize the total area of the larger rectangle required to pack all the items. Given the widths and heig... | widths = [3, 4, 2, 1] # Widths of the items heights = [2, 3, 1, 4] # Heights of the items | # Data
widths = [3, 4, 2, 1] # Widths of the items
heights = [2, 3, 1, 4] # Heights of the items
# End of data
# Import libraries
from cpmpy import *
import json
from cpmpy.expressions.utils import all_pairs
def model_packing_rectangular(widths, heights):
# Number of different items
n = len(widths)
# ... | [
"total_y",
"pos_x",
"pos_y",
"total_x"
] |
cpmpy_examples__resource_constrained_project_scheduling | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/rcpsp.py",
"# Description: https://python-mip.readthedocs.io/en/latest/examples.html#resource-constrained-project-scheduling"
] | The resource-constrained project scheduling problem involves scheduling a set of jobs, each with a specific duration and resource requirement, such that the total project duration (makespan) is minimized. Each job may have precedence constraints, meaning certain jobs must be completed before others can start. Additiona... | durations_data = [0, 3, 2, 5, 4, 2, 3, 4, 2, 4, 6, 0] resource_needs_data = [[0, 0], [5, 1], [0, 4], [1, 4], [1, 3], [3, 2], [3, 1], [2, 4], [4, 0], [5, 2], [2, 5], [0, 0]] resource_capacities_data = [6, 8] successors_link_data = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 9], [2, 10], [3, 8], [4, 6], [4, 7], [5, 9], ... | # Data
durations_data = [0, 3, 2, 5, 4, 2, 3, 4, 2, 4, 6, 0]
resource_needs_data = [[0, 0], [5, 1], [0, 4], [1, 4], [1, 3], [3, 2], [3, 1], [2, 4], [4, 0], [5, 2], [2, 5], [0, 0]]
resource_capacities_data = [6, 8]
successors_link_data = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 9], [2, 10], [3, 8], [4, 6], [4, 7], [... | [
"start_time"
] |
cpmpy_examples__room_assignment | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/room_assignment.ipynb"
] | The room assignment problem involves assigning a set of requests to a limited number of rooms such that each request is assigned to one room for its entire duration. Some requests may already have a room pre-assigned. The main constraint is that a room can only serve one request at a time, meaning no overlapping reques... | max_rooms = 5 # Maximum number of rooms available start_data = ["2024-05-01", "2024-05-02", "2024-05-03", "2024-05-04"] # Start date of the requests end_data = ["2024-05-05", "2024-05-06", "2024-05-07", "2024-05-08"] # End date of the requests preassigned_room_data = [3, -1, -1, -1] # Room 3 pre-assigned for the fi... | # Data
max_rooms = 5 # Maximum number of rooms available
start_data = ["2024-05-01", "2024-05-02", "2024-05-03", "2024-05-04"] # Start date of the requests
end_data = ["2024-05-05", "2024-05-06", "2024-05-07", "2024-05-08"] # End date of the requests
preassigned_room_data = [3, -1, -1, -1] # Room 3 pre-assigned for... | [
"room_assignments"
] |
cpmpy_examples__send_more_money | cpmpy_examples | [
"#!/usr/bin/python3",
"# Source: https://github.com/CPMpy/cpmpy/blob/master/examples/send_more_money.py"
] | Send More Money Puzzle The "Send More Money" puzzle is a classic cryptarithmetic problem where each letter represents a unique digit. The goal is to assign digits to the letters such that the following equation holds true: SEND + MORE ------ MONEY Each letter must be assigned a unique digit from 0 to 9, and t... | # Import libraries
from cpmpy import *
import numpy as np
import json
# Decision variables
s, e, n, d, m, o, r, y = intvar(0, 9, shape=8)
model = Model(
AllDifferent([s, e, n, d, m, o, r, y]),
(sum([s, e, n, d] * np.array([1000, 100, 10, 1])) \
+ sum([m, o, r, e] * np.array([1000, 100, 10, 1])) \
==... | [
"y",
"e",
"s",
"r",
"o",
"d",
"m",
"n"
] |
CP-Bench: A dataset for evaluating LLM-driven constraint modelling
This dataset is designed to facilitate the evaluation of LLM-based methods for translating natural language problem descriptions into accurate constraint specifications. It contains diverse combinatorial problems, and is sourced from various well-established sources from the Constraint Programming community.
Dataset Versions
You will notice that the dataset contains various splits (which are not exactly splits, but rather different versions of the dataset):
original: The original dataset, which contains all problems initially designed, including those with known issues. More details about the issues can be found in the changelog.verified: A stripped-down version of the original dataset that has been verified to contain complete problem specifications with matching ground-truth models. This version is recommended for use in evaluations.
π Leaderboard
You can easily submit your results and view the global leaderboard here:
π CP-Bench Leaderboard
Dataset Breakdown
The dataset contains problems from the following sources:
aplai_course: Problems from the APLAI course of KU Leuven, 2023-2024. As modelled here.cpmpy_examples: Problems from the CPMpy repository- All included, except for the ones that require enumeration of all solutions (e.g.
solveAll).
- All included, except for the ones that require enumeration of all solutions (e.g.
csplib- For now, only the ones modelled in the CPMpy repository are included, and the ones modelled by Hakan Kjellerstrand.
hakan_examples: Models created by Hakan Kjellerstrand- In progress with alphabetical order, excluding the following:
- Those already modelled from other sources (e.g. aplai_course, cpmpy_examples, csplib)
- Those that contain
solveAll(counting solutions). - Global constraints tests, e.g. http://www.hakank.org/cpmpy/atmost_test.py
- In progress with alphabetical order, excluding the following:
Diversity
We attempted to include unique problems from different sources, in order to provide a diverse set of problems. However, as this was a manual process, there might be duplicates or similar problems. If you notice any issues, please let us know.
Citation
If you found our work useful, please consider citing it:
@misc{michailidis2025cpbench,
title={CP-Bench: Evaluating Large Language Models for Constraint Modelling},
author={Kostis Michailidis and Dimos Tsouros and Tias Guns},
year={2025},
eprint={2506.06052},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2506.06052},
}
- Downloads last month
- 11