reindent all python code

This commit is contained in:
lperron@google.com
2014-05-22 20:13:16 +00:00
parent 87e0940b36
commit b3c56a368f
140 changed files with 8723 additions and 8727 deletions

View File

@@ -25,12 +25,14 @@
http://www.hakank.org/google_or_tools/3_jugs_regular
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -41,20 +43,19 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
#
n = 15
start = 0 # start node
start = 0 # start node
end = 14 # end node
M = 999 # a large number
nodes = ['8,0,0', # start
nodes = ['8,0,0', # start
'5,0,3',
'5,3,0',
'2,3,3',
@@ -88,7 +89,6 @@ def main(sol = 'GLPK'):
[M, 1, M, M, M, M, M, M, M, M, M, M, M, M, 1],
[M, M, M, M, M, M, M, M, M, M, M, M, M, M, M]]
#
# variables
#
@@ -99,21 +99,20 @@ def main(sol = 'GLPK'):
x = {}
for i in range(n):
for j in range(n):
x[i,j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
x[i, j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
out_flow = [solver.IntVar(0, 1, 'out_flow[%i]' % i) for i in range(n)]
in_flow = [solver.IntVar(0, 1, 'in_flow[%i]' % i) for i in range(n)]
# length of path, to be minimized
z = solver.Sum([d[i][j]*x[i,j]
for i in range(n)
for j in range(n) if d[i][j] < M])
z = solver.Sum([d[i][j] * x[i, j]
for i in range(n)
for j in range(n) if d[i][j] < M])
#
# constraints
#
for i in range(n):
if i == start:
solver.Add(rhs[i] == 1)
@@ -122,28 +121,25 @@ def main(sol = 'GLPK'):
else:
solver.Add(rhs[i] == 0)
# outflow constraint
for i in range(n):
solver.Add(out_flow[i] == solver.Sum([x[i,j]
solver.Add(out_flow[i] == solver.Sum([x[i, j]
for j in range(n)
if d[i][j] < M]))
# inflow constraint
for j in range(n):
solver.Add(in_flow[j] == solver.Sum([x[i,j]
solver.Add(in_flow[j] == solver.Sum([x[i, j]
for i in range(n)
if d[i][j] < M]))
# inflow = outflow
for i in range(n):
solver.Add(out_flow[i]-in_flow[i] == rhs[i])
solver.Add(out_flow[i] - in_flow[i] == rhs[i])
# objective
objective = solver.Minimize(z)
#
# solution and search
#
@@ -156,7 +152,7 @@ def main(sol = 'GLPK'):
while t != end:
print nodes[t], '->',
for j in range(n):
if x[t,j].SolutionValue() == 1:
if x[t, j].SolutionValue() == 1:
print nodes[j]
t = j
break

View File

@@ -43,7 +43,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -70,197 +71,196 @@ from collections import defaultdict
# d : transition matrix
# q0: initial state
# F : accepting states
def regular(x, Q, S, d, q0, F):
solver = x[0].solver()
solver = x[0].solver()
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q+1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i-1][j])
d2.append(row)
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q + 1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i - 1][j])
d2.append(row)
d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)]
d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
m = 0
n = len(x)
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1)))
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(
a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))
def main(n):
# Create the solver.
solver = pywrapcp.Solver('3 jugs problem using regular constraint')
# Create the solver.
solver = pywrapcp.Solver('3 jugs problem using regular constraint')
#
# data
#
#
# data
#
# the DFA (for regular)
n_states = 14
input_max = 15
initial_state = 1 # 0 is for the failing state
accepting_states = [15]
# the DFA (for regular)
n_states = 14
input_max = 15
initial_state = 1 # 0 is for the failing state
accepting_states = [15]
##
## Manually crafted DFA
## (from the adjacency matrix used in the other models)
##
# transition_fn = [
# # 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
# [0, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 1
# [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2
# [0, 0, 0, 4, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 3
# [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 4
# [0, 0, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 5
# [0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], # 6
# [0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0], # 7
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 8
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0], # 9
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0], # 10
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0], # 11
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0], # 12
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0], # 13
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 14
# # 15
# ]
##
# Manually crafted DFA
# (from the adjacency matrix used in the other models)
##
# transition_fn = [
# # 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
# [0, 2, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 1
# [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 2
# [0, 0, 0, 4, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 3
# [0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 4
# [0, 0, 0, 0, 0, 6, 0, 0, 9, 0, 0, 0, 0, 0, 0], # 5
# [0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0], # 6
# [0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0], # 7
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 8
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0], # 9
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0], # 10
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0], # 11
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0], # 12
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0], # 13
# [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15], # 14
# # 15
# ]
#
# However, the DFA is easy to create from adjacency lists.
#
states = [
[2,9], # state 1
[3], # state 2
[4, 9], # state 3
[5], # state 4
[6,9], # state 5
[7], # state 6
[8,9], # state 7
[15], # state 8
[10], # state 9
[11], # state 10
[12], # state 11
[13], # state 12
[14], # state 13
[15] # state 14
]
#
# However, the DFA is easy to create from adjacency lists.
#
states = [
[2, 9], # state 1
[3], # state 2
[4, 9], # state 3
[5], # state 4
[6, 9], # state 5
[7], # state 6
[8, 9], # state 7
[15], # state 8
[10], # state 9
[11], # state 10
[12], # state 11
[13], # state 12
[14], # state 13
[15] # state 14
]
transition_fn = []
for i in range(n_states):
row = []
for j in range(1,input_max+1):
if j in states[i]:
row.append(j)
else:
row.append(0)
transition_fn.append(row)
transition_fn = []
for i in range(n_states):
row = []
for j in range(1, input_max + 1):
if j in states[i]:
row.append(j)
else:
row.append(0)
transition_fn.append(row)
#
# The name of the nodes, for printing
# the solution.
#
nodes = [
'8,0,0', # 1 start
'5,0,3', # 2
'5,3,0', # 3
'2,3,3', # 4
'2,5,1', # 5
'7,0,1', # 6
'7,1,0', # 7
'4,1,3', # 8
'3,5,0', # 9
'3,2,3', # 10
'6,2,0', # 11
'6,0,2', # 12
'1,5,2', # 13
'1,4,3', # 14
'4,4,0' # 15 goal
]
#
# The name of the nodes, for printing
# the solution.
#
nodes = [
'8,0,0', # 1 start
'5,0,3', # 2
'5,3,0', # 3
'2,3,3', # 4
'2,5,1', # 5
'7,0,1', # 6
'7,1,0', # 7
'4,1,3', # 8
'3,5,0', # 9
'3,2,3', # 10
'6,2,0', # 11
'6,0,2', # 12
'1,5,2', # 13
'1,4,3', # 14
'4,4,0' # 15 goal
]
#
# declare variables
#
x = [solver.IntVar(1, input_max, 'x[%i]' % i) for i in range(n)]
#
# declare variables
#
x = [solver.IntVar(1, input_max, 'x[%i]'% i) for i in range(n)]
#
# constraints
#
regular(x, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# constraints
#
regular(x, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
num_solutions = 0
x_val = []
while solver.NextSolution():
num_solutions += 1
x_val = [1] + [x[i].Value() for i in range(n)]
print 'x:', x_val
for i in range(1, n + 1):
print '%s -> %s' % (nodes[x_val[i - 1] - 1], nodes[x_val[i] - 1])
solver.NewSearch(db)
solver.EndSearch()
num_solutions = 0
x_val = []
while solver.NextSolution():
num_solutions += 1
x_val = [1] + [x[i].Value() for i in range(n)]
print 'x:', x_val
for i in range(1, n+1):
print '%s -> %s' % (nodes[x_val[i-1]-1], nodes[x_val[i]-1])
if num_solutions > 0:
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
solver.EndSearch()
if num_solutions > 0:
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
# return the solution (or an empty array)
return x_val
# return the solution (or an empty array)
return x_val
# Search for a minimum solution by increasing
# the length of the state array.
if __name__ == '__main__':
for n in range(1, 15):
result = main(n)
result_len = len(result)
if result_len:
print '\nFound a solution of length %i:' % result_len,
print result
print
break
for n in range(1, 15):
result = main(n)
result_len = len(result)
if result_len:
print '\nFound a solution of length %i:' % result_len,
print result
print
break

View File

@@ -60,107 +60,107 @@
* SICStus : http://hakank.org/sicstus/a_round_of_golf.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('All interval')
# Create the solver.
solver = pywrapcp.Solver("All interval")
#
# data
#
n = 4
[Jack, Bill, Paul, Frank] = [i for i in range(n)]
#
# data
#
n = 4
[Jack, Bill, Paul, Frank] = [i for i in range(n)]
#
# declare variables
#
last_name = [solver.IntVar(0, n-1, 'last_name[%i]' % i) for i in range(n)]
[Green, Clubb, Sands, Carter] = last_name
#
# declare variables
#
last_name = [solver.IntVar(0, n - 1, "last_name[%i]" % i) for i in range(n)]
[Green, Clubb, Sands, Carter] = last_name
job = [solver.IntVar(0, n-1, 'job[%i]' % i) for i in range(n)]
[cook, maintenance_man, clerk, caddy] = job
job = [solver.IntVar(0, n - 1, "job[%i]" % i) for i in range(n)]
[cook, maintenance_man, clerk, caddy] = job
score = [solver.IntVar(70, 85, 'score[%i]' % i) for i in range(n)]
score = [solver.IntVar(70, 85, "score[%i]" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(last_name))
solver.Add(solver.AllDifferent(job))
solver.Add(solver.AllDifferent(score))
#
# constraints
#
solver.Add(solver.AllDifferent(last_name))
solver.Add(solver.AllDifferent(job))
solver.Add(solver.AllDifferent(score))
# 1. Bill, who is not the maintenance man, plays golf often and had
# the lowest score of the foursome.
solver.Add(Bill != maintenance_man)
solver.Add(score[Bill] < score[Jack])
solver.Add(score[Bill] < score[Paul])
solver.Add(score[Bill] < score[Frank])
# 1. Bill, who is not the maintenance man, plays golf often and had
# the lowest score of the foursome.
solver.Add(Bill != maintenance_man)
solver.Add(score[Bill] < score[Jack])
solver.Add(score[Bill] < score[Paul])
solver.Add(score[Bill] < score[Frank])
# 2. Mr. Clubb, who isn't Paul, hit several balls into the woods and
# scored ten strokes more than the pro-shop clerk.
solver.Add(Clubb != Paul)
solver.Add(solver.Element(score, Clubb) == solver.Element(score, clerk) + 10)
# 2. Mr. Clubb, who isn't Paul, hit several balls into the woods and
# scored ten strokes more than the pro-shop clerk.
solver.Add(Clubb != Paul)
solver.Add(solver.Element(score, Clubb) == solver.Element(score, clerk) + 10)
# 3. In some order, Frank and the caddy scored four and seven more
# strokes than Mr. Sands.
solver.Add(Frank != caddy)
solver.Add(Frank != Sands)
solver.Add(caddy != Sands)
# 3. In some order, Frank and the caddy scored four and seven more
# strokes than Mr. Sands.
solver.Add(Frank != caddy)
solver.Add(Frank != Sands)
solver.Add(caddy != Sands)
b3_a_1 = solver.IsEqualVar(solver.Element(score, Sands) + 4, \
score[Frank])
b3_a_2 = solver.IsEqualVar(solver.Element(score, caddy), \
solver.Element(score, Sands) + 7)
b3_a_1 = solver.IsEqualVar(solver.Element(score, Sands) + 4,
score[Frank])
b3_a_2 = solver.IsEqualVar(solver.Element(score, caddy),
solver.Element(score, Sands) + 7)
b3_b_1 = solver.IsEqualVar(solver.Element(score, Sands) + 7, \
score[Frank])
b3_b_2 = solver.IsEqualVar(solver.Element(score, caddy), \
solver.Element(score, Sands) + 4)
b3_b_1 = solver.IsEqualVar(solver.Element(score, Sands) + 7,
score[Frank])
b3_b_2 = solver.IsEqualVar(solver.Element(score, caddy),
solver.Element(score, Sands) + 4)
solver.Add( (b3_a_1*b3_a_2) + (b3_b_1*b3_b_2) == 1)
solver.Add((b3_a_1 * b3_a_2) + (b3_b_1 * b3_b_2) == 1)
# 4. Mr. Carter thought his score of 78 was one of his better games,
# even though Frank's score was lower.
solver.Add(Frank != Carter)
solver.Add(solver.Element(score, Carter) == 78)
solver.Add(score[Frank] < solver.Element(score, Carter))
# 4. Mr. Carter thought his score of 78 was one of his better games,
# even though Frank's score was lower.
solver.Add(Frank != Carter)
solver.Add(solver.Element(score,Carter) == 78)
solver.Add(score[Frank] < solver.Element(score,Carter))
# 5. None of the four scored exactly 81 strokes.
[solver.Add(score[i] != 81) for i in range(n)]
# 5. None of the four scored exactly 81 strokes.
[solver.Add(score[i] != 81) for i in range(n)]
#
# solution and search
#
solution = solver.Assignment()
solution.Add(last_name)
solution.Add(job)
solution.Add(score)
db = solver.Phase(last_name + job + score,
solver.CHOOSE_FIRST_UNBOUND,
solver.INT_VALUE_DEFAULT)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(last_name)
solution.Add(job)
solution.Add(score)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "last_name:", [last_name[i].Value() for i in range(n)]
print "job :", [job[i].Value() for i in range(n)]
print "score :", [score[i].Value() for i in range(n)]
num_solutions += 1
print
db = solver.Phase(last_name + job + score,
solver.CHOOSE_FIRST_UNBOUND,
solver.INT_VALUE_DEFAULT)
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "last_name:", [last_name[i].Value() for i in range(n)]
print "job :", [job[i].Value() for i in range(n)]
print "score :", [score[i].Value() for i in range(n)]
num_solutions += 1
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -46,68 +46,71 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import string, sys
import string
import sys
from ortools.constraint_solver import pywrapcp
def main(n=12):
# Create the solver.
solver = pywrapcp.Solver('All interval')
# Create the solver.
solver = pywrapcp.Solver("All interval")
#
# data
#
print "n:", n
#
# data
#
print "n:", n
#
# declare variables
#
x = [solver.IntVar(1, n, 'x[%i]' % i) for i in range(n)]
diffs = [solver.IntVar(1, n-1, 'diffs[%i]' % i) for i in range(n-1)]
#
# declare variables
#
x = [solver.IntVar(1, n, "x[%i]" % i) for i in range(n)]
diffs = [solver.IntVar(1, n - 1, "diffs[%i]" % i) for i in range(n - 1)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
solver.Add(solver.AllDifferent(diffs))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
solver.Add(solver.AllDifferent(diffs))
for k in range(n-1):
solver.Add(diffs[k] == abs(x[k+1]-x[k]))
for k in range(n - 1):
solver.Add(diffs[k] == abs(x[k + 1] - x[k]))
# symmetry breaking
solver.Add(x[0] < x[n-1])
solver.Add(diffs[0] < diffs[1])
# symmetry breaking
solver.Add(x[0] < x[n - 1])
solver.Add(diffs[0] < diffs[1])
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(diffs)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(diffs)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "x:", [x[i].Value() for i in range(n)]
print "diffs:", [diffs[i].Value() for i in range(n-1)]
num_solutions += 1
print
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "x:", [x[i].Value() for i in range(n)]
print "diffs:", [diffs[i].Value() for i in range(n - 1)]
num_solutions += 1
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
n=12
if __name__ == '__main__':
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
n = 12
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)

View File

@@ -44,13 +44,12 @@
* Zinc: http://hakank.org/minizinc/alldifferent_except_0.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
#
@@ -58,65 +57,67 @@ from ortools.constraint_solver import pywrapcp
# Thanks to Laurent Perron (Google) for
# suggestions of improvements.
#
def alldifferent_except_0(solver, a):
n = len(a)
for i in range(n):
for j in range(i):
solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j]))
n = len(a)
for i in range(n):
for j in range(i):
solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j]))
# more compact version:
def alldifferent_except_0_b(solver, a):
n = len(a)
[solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j]))
for i in range(n) for j in range(i)]
n = len(a)
[solver.Add((a[i] != 0) * (a[j] != 0) <= (a[i] != a[j]))
for i in range(n) for j in range(i)]
def main(unused_argv):
# Create the solver.
solver = pywrapcp.Solver('Alldifferent except 0')
# Create the solver.
solver = pywrapcp.Solver("Alldifferent except 0")
# data
n = 7
# data
n = 7
# declare variables
x = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)]
# Number of zeros.
z = solver.Sum([x[i] == 0 for i in range(n)]).VarWithName('z')
# declare variables
x = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
# Number of zeros.
z = solver.Sum([x[i] == 0 for i in range(n)]).VarWithName("z")
#
# constraints
#
alldifferent_except_0(solver, x)
#
# constraints
#
alldifferent_except_0(solver, x)
# we require 2 0's
solver.Add(z == 2)
# we require 2 0's
solver.Add(z == 2)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([x[i] for i in range(n)])
solution.Add(z)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([x[i] for i in range(n)])
solution.Add(z)
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase([x[i] for i in range(n)],
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase([x[i] for i in range(n)],
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(n)]
print "z:", collector.Value(s, z)
print
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(n)]
print "z:", collector.Value(s, z)
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main("cp sample")
if __name__ == "__main__":
main("cp sample")

View File

@@ -40,127 +40,130 @@
* Zinc: http://www.hakank.org/minizinc/alphametic.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string, re
import sys
import string
import re
from ortools.constraint_solver import pywrapcp
def main(problem_str="SEND+MORE=MONEY", base=10):
# Create the solver.
solver = pywrapcp.Solver('Send most money')
# Create the solver.
solver = pywrapcp.Solver("Send most money")
# data
print "\nproblem:", problem_str
# data
print "\nproblem:", problem_str
# convert to array.
problem = re.split("[\s+=]", problem_str)
# convert to array.
problem = re.split("[\s+=]", problem_str)
p_len = len(problem)
print "base:", base
p_len = len(problem)
print "base:", base
# create the lookup table: list of (digit : ix)
a = sorted(set("".join(problem)))
n = len(a)
lookup = dict(zip(a, range(n)))
# create the lookup table: list of (digit : ix)
a = sorted(set("".join(problem)))
n = len(a)
lookup = dict(zip(a, range(n)))
# length of each number
lens = map(len, problem)
# length of each number
lens = map(len, problem)
#
# declare variables
#
#
# declare variables
#
# the digits
x = [solver.IntVar(0, base-1, "x[%i]"%i) for i in range(n)]
# the sums of each number (e.g. the three numbers SEND, MORE, MONEY)
sums = [solver.IntVar(1, 10**(lens[i])-1) for i in range(p_len)]
# the digits
x = [solver.IntVar(0, base - 1, "x[%i]" % i) for i in range(n)]
# the sums of each number (e.g. the three numbers SEND, MORE, MONEY)
sums = [solver.IntVar(1, 10 ** (lens[i]) - 1) for i in range(p_len)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
ix = 0
ix = 0
for prob in problem:
this_len = len(prob)
# sum all the digits with proper exponents to a number
solver.Add(sums[ix] == solver.Sum(
[(base ** i) * x[lookup[prob[this_len - i - 1]]] for i in range(this_len)[::-1]]))
# leading digits must be > 0
solver.Add(x[lookup[prob[0]]] > 0)
ix += 1
# the last number is the sum of the previous numbers
solver.Add(solver.Sum([sums[i] for i in range(p_len - 1)]) == sums[-1])
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(sums)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nsolution #%i" % num_solutions
for i in range(n):
print a[i], "=", x[i].Value()
print
for prob in problem:
this_len = len(prob)
for p in prob:
print p,
print
print
for prob in problem:
for p in prob:
print x[lookup[p]].Value(),
print
# sum all the digits with proper exponents to a number
solver.Add(sums[ix] == solver.Sum([(base**i)*x[lookup[prob[this_len-i-1]]]
for i in range(this_len)[::-1]]))
# leading digits must be > 0
solver.Add(x[lookup[prob[0]]] > 0)
ix += 1
print "sums:", [sums[i].Value() for i in range(p_len)]
print
# the last number is the sum of the previous numbers
solver.Add(solver.Sum([sums[i] for i in range(p_len-1)]) == sums[-1])
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(sums)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nsolution #%i" % num_solutions
for i in range(n):
print a[i], "=", x[i].Value()
print
for prob in problem:
for p in prob:
print p,
print
print
for prob in problem:
for p in prob:
print x[lookup[p]].Value(),
print
print "sums:", [sums[i].Value() for i in range(p_len)]
print
print "\nnum_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "\nnum_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
def test_problems(base=10):
problems = [
"SEND+MORE=MONEY",
"SEND+MOST=MONEY",
"VINGT+CINQ+CINQ=TRENTE",
"EIN+EIN+EIN+EIN=VIER",
"DONALD+GERALD=ROBERT",
"SATURN+URANUS+NEPTUNE+PLUTO+PLANETS",
"WRONG+WRONG=RIGHT"
]
problems = [
"SEND+MORE=MONEY",
"SEND+MOST=MONEY",
"VINGT+CINQ+CINQ=TRENTE",
"EIN+EIN+EIN+EIN=VIER",
"DONALD+GERALD=ROBERT",
"SATURN+URANUS+NEPTUNE+PLUTO+PLANETS",
"WRONG+WRONG=RIGHT"
]
for p in problems:
main(p, base)
for p in problems:
main(p, base)
problem = "SEND+MORE=MONEY"
base = 10
if __name__ == '__main__':
if len(sys.argv) > 1:
problem = sys.argv[1]
if len(sys.argv) > 2:
base = string.atoi(sys.argv[2])
if __name__ == "__main__":
if len(sys.argv) > 1:
problem = sys.argv[1]
if len(sys.argv) > 2:
base = string.atoi(sys.argv[2])
if problem == "TEST" or problem == "test":
test_problems(base)
else:
main(problem, base)
if problem == "TEST" or problem == "test":
test_problems(base)
else:
main(problem, base)

View File

@@ -84,7 +84,7 @@ def Select(combinations, loads, max_number_of_workers):
# Simple bound.
solver.Add(solver.Sum(variables) <= max_number_of_workers)
obj_vars = [solver.IntVar(0, 1000, 'obj_vars[%d]' %i)
obj_vars = [solver.IntVar(0, 1000, 'obj_vars[%d]' % i)
for i in range(num_vars)]
for i in range(num_vars):
solver.Add(obj_vars[i] >= achieved[i] - loads[i])

View File

@@ -28,85 +28,88 @@
* SICStus: http://hakank.org/sicstus/assignment.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main(cost, rows, cols):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
#
# data
#
# declare variables
total_cost = solver.IntVar(0, 100, "total_cost")
x = []
for i in range(rows):
t = []
for j in range(cols):
t.append(solver.IntVar(0, 1, "x[%i,%i]" % (i, j)))
x.append(t)
x_flat = [x[i][j] for i in range(rows) for j in range(cols)]
# declare variables
total_cost = solver.IntVar(0, 100, 'total_cost')
x = []
#
# constraints
#
# total_cost
solver.Add(
total_cost == solver.Sum(
[solver.ScalProd(x_row, cost_row) for (x_row, cost_row) in zip(
x, cost)]))
# exacly one assignment per row, all rows must be assigned
[solver.Add(solver.Sum([x[row][j] for j in range(cols)]) == 1)
for row in range(rows)]
# zero or one assignments per column
[solver.Add(solver.Sum([x[i][col] for i in range(rows)]) <= 1)
for col in range(cols)]
objective = solver.Minimize(total_cost, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(total_cost)
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "total_cost:", total_cost.Value()
for i in range(rows):
t = []
for j in range(cols):
t.append(solver.IntVar(0,1, 'x[%i,%i]'%(i,j)))
x.append(t)
x_flat = [x[i][j] for i in range(rows) for j in range(cols)]
#
# constraints
#
# total_cost
solver.Add(total_cost == solver.Sum([solver.ScalProd(x_row, cost_row) for (x_row, cost_row) in zip(x, cost)]))
# exacly one assignment per row, all rows must be assigned
[solver.Add(solver.Sum([x[row][j] for j in range(cols)]) == 1) for row in range(rows)]
# zero or one assignments per column
[solver.Add(solver.Sum([x[i][col] for i in range(rows)]) <= 1) for col in range(cols)]
objective = solver.Minimize(total_cost, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(total_cost)
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db,[objective])
num_solutions = 0
while solver.NextSolution():
print "total_cost:", total_cost.Value()
for i in range(rows):
for j in range(cols):
print x[i][j].Value(),
print
print
for i in range(rows):
print "Task:",i,
for j in range(cols):
if x[i][j].Value() == 1:
print " is done by ", j
print
num_solutions += 1
solver.EndSearch()
for j in range(cols):
print x[i][j].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
for i in range(rows):
print "Task:", i,
for j in range(cols):
if x[i][j].Value() == 1:
print " is done by ", j
print
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
# Problem instance
@@ -114,11 +117,10 @@ def main(cost, rows, cols):
# interesting
rows = 4
cols = 5
cost = [[14, 5, 8, 7, 15],
[ 2, 12, 6, 5, 3],
[ 7, 8, 3, 9, 7],
[ 2, 4, 6, 10, 1]
]
cost = [[14, 5, 8, 7, 15],
[2, 12, 6, 5, 3],
[7, 8, 3, 9, 7],
[2, 4, 6, 10, 1]]
if __name__ == '__main__':
main(cost, rows, cols)
if __name__ == "__main__":
main(cost, rows, cols)

View File

@@ -37,12 +37,14 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -53,10 +55,9 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
@@ -80,14 +81,14 @@ def main(sol = 'GLPK'):
#
# Optimal solution is 76
# """
c = [[13, 21, 20, 12, 8, 26, 22, 11],
[12, 36, 25, 41, 40, 11, 4, 8],
c = [[13, 21, 20, 12, 8, 26, 22, 11],
[12, 36, 25, 41, 40, 11, 4, 8],
[35, 32, 13, 36, 26, 21, 13, 37],
[34, 54, 7, 8, 12, 22, 11, 40],
[21, 6, 45, 18, 24, 34, 12, 48],
[34, 54, 7, 8, 12, 22, 11, 40],
[21, 6, 45, 18, 24, 34, 12, 48],
[42, 19, 39, 15, 14, 16, 28, 46],
[16, 34, 38, 3, 34, 40, 22, 24],
[26, 20, 5, 17, 45, 31, 37, 43]]
[16, 34, 38, 3, 34, 40, 22, 24],
[26, 20, 5, 17, 45, 31, 37, 43]]
#
# variables
@@ -101,35 +102,32 @@ def main(sol = 'GLPK'):
x = {}
for i in range(n):
for j in range(n):
x[i,j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
x[i, j] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
# total cost, to be minimized
z = solver.Sum([c[i][j]*x[i,j]
for i in I
for j in J])
z = solver.Sum([c[i][j] * x[i, j]
for i in I
for j in J])
#
# constraints
#
# each agent can perform at most one task
for i in I:
solver.Add(solver.Sum([x[i,j] for j in J]) <= 1)
solver.Add(solver.Sum([x[i, j] for j in J]) <= 1)
# each task must be assigned exactly to one agent
for j in J:
solver.Add(solver.Sum([x[i,j] for i in I]) == 1)
solver.Add(solver.Sum([x[i, j] for i in I]) == 1)
# to which task and what cost is person i assigned (for output in MiniZinc)
for i in I:
solver.Add(assigned[i] == solver.Sum([ j*x[i,j] for j in J]))
solver.Add(costs[i] == solver.Sum([c[i][j]*x[i,j] for j in J]))
solver.Add(assigned[i] == solver.Sum([j * x[i, j] for j in J]))
solver.Add(costs[i] == solver.Sum([c[i][j] * x[i, j] for j in J]))
# objective
objective = solver.Minimize(z)
#
# solution and search
#
@@ -146,12 +144,10 @@ def main(sol = 'GLPK'):
print 'Matrix:'
for i in I:
for j in J:
print int(x[i,j].SolutionValue()),
print int(x[i, j].SolutionValue()),
print
print
print
print 'walltime :', solver.WallTime(), 'ms'
if sol == 'CBC':

View File

@@ -23,34 +23,35 @@ gflags.DEFINE_string('data', 'python/data/bacp/bacp12.txt',
#----------------helper for binpacking posting----------------
def BinPacking(solver, binvars, weights, loadvars):
'''post the load constraint on bins.
constraints forall j: loadvars[j] == sum_i (binvars[i] == j) * weights[i])
'''
pack = solver.Pack(binvars, len(loadvars))
pack.AddWeightedSumEqualVarDimension(weights, loadvars);
pack.AddWeightedSumEqualVarDimension(weights, loadvars)
solver.Add(pack)
solver.Add(solver.SumEquality(loadvars, sum(weights)))
#------------------------------data reading-------------------
def ReadData(filename):
'''Read data from <filename>.'''
"""Read data from <filename>."""
f = open(filename)
nb_courses, nb_periods, min_credit, max_credit, nb_prereqs =\
[int(nb) for nb in f.readline().split()]
credits = [int(nb) for nb in f.readline().split()]
prereq = [int(nb) for nb in f.readline().split()]
prereq = [(prereq[i * 2],prereq[i * 2 + 1]) for i in range(nb_prereqs)]
return (credits ,nb_periods, prereq)
prereq = [int(nb) for nb in f.readline().split()]
prereq = [(prereq[i * 2], prereq[i * 2 + 1]) for i in range(nb_prereqs)]
return (credits, nb_periods, prereq)
def main(unused_argv):
#------------------solver and variable declaration-------------
credits ,nb_periods, prereq = ReadData(FLAGS.data)
credits, nb_periods, prereq = ReadData(FLAGS.data)
nb_courses = len(credits)
solver = pywrapcp.Solver('Balanced Academic Curriculum Problem')
@@ -65,8 +66,8 @@ def main(unused_argv):
# Bin Packing.
BinPacking(solver, x, credits, load_vars)
# Add dependencies.
for i,j in prereq:
solver.Add(x[i] < x[j])
for i, j in prereq:
solver.Add(x[i] < x[j])
#----------------Objective-------------------------------

View File

@@ -19,13 +19,14 @@
From the OPL model blending.mod.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -36,10 +37,9 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
@@ -54,15 +54,15 @@ def main(sol = 'GLPK'):
Ingos = range(NbIngo)
CostMetal = [22, 10, 13]
CostRaw = [6, 5]
CostScrap = [ 7, 8]
CostIngo = [9 ]
Low = [0.05, 0.30, 0.60]
Up = [0.10, 0.40, 0.80]
PercRaw = [ [ 0.20, 0.01 ], [ 0.05, 0 ], [ 0.05, 0.30 ] ]
PercScrap = [ [ 0 , 0.01 ], [ 0.60, 0 ], [ 0.40, 0.70 ] ]
PercIngo = [ [ 0.10 ], [ 0.45 ], [ 0.45 ] ]
Alloy = 71
CostRaw = [6, 5]
CostScrap = [7, 8]
CostIngo = [9]
Low = [0.05, 0.30, 0.60]
Up = [0.10, 0.40, 0.80]
PercRaw = [[0.20, 0.01], [0.05, 0], [0.05, 0.30]]
PercScrap = [[0, 0.01], [0.60, 0], [0.40, 0.70]]
PercIngo = [[0.10], [0.45], [0.45]]
Alloy = 71
#
# variables
@@ -71,7 +71,7 @@ def main(sol = 'GLPK'):
r = [solver.NumVar(0, solver.Infinity(), 'r[%i]' % i) for i in Raws]
s = [solver.NumVar(0, solver.Infinity(), 's[%i]' % i) for i in Scraps]
ii = [solver.IntVar(0, solver.Infinity(), 'ii[%i]' % i) for i in Ingos]
metal = [solver.NumVar(Low[j]*Alloy, Up[j]*Alloy, 'metal[%i]' % j)
metal = [solver.NumVar(Low[j] * Alloy, Up[j] * Alloy, 'metal[%i]' % j)
for j in Metals]
z = solver.NumVar(0, solver.Infinity(), 'z')
@@ -81,19 +81,17 @@ def main(sol = 'GLPK'):
#
solver.Add(z ==
solver.Sum([CostMetal[i] * p[i] for i in Metals]) +
solver.Sum([CostRaw[i] * r[i] for i in Raws]) +
solver.Sum([CostScrap[i] * s[i] for i in Scraps]) +
solver.Sum([CostIngo[i] * ii[i] for i in Ingos]))
solver.Sum([CostMetal[i] * p[i] for i in Metals]) +
solver.Sum([CostRaw[i] * r[i] for i in Raws]) +
solver.Sum([CostScrap[i] * s[i] for i in Scraps]) +
solver.Sum([CostIngo[i] * ii[i] for i in Ingos]))
for j in Metals:
solver.Add(
metal[j] == p[j] +
solver.Sum([PercRaw[j][k] * r[k] for k in Raws]) +
solver.Sum([PercScrap[j][k] * s[k] for k in Scraps]) +
solver.Sum([PercIngo[j][k] * ii[k] for k in Ingos]))
metal[j] == p[j] +
solver.Sum([PercRaw[j][k] * r[k] for k in Raws]) +
solver.Sum([PercScrap[j][k] * s[k] for k in Scraps]) +
solver.Sum([PercIngo[j][k] * ii[k] for k in Ingos]))
solver.Add(solver.Sum(metal) == Alloy)
@@ -140,12 +138,12 @@ def main(sol = 'GLPK'):
if __name__ == '__main__':
sol = 'GLPK'
sol = 'GLPK'
if len(sys.argv) > 1:
sol = sys.argv[1]
if sol != 'GLPK' and sol != 'CBC':
print 'Solver must be either GLPK or CBC'
sys.exit(1)
if len(sys.argv) > 1:
sol = sys.argv[1]
if sol != 'GLPK' and sol != 'CBC':
print 'Solver must be either GLPK or CBC'
sys.exit(1)
main(sol)
main(sol)

View File

@@ -44,7 +44,8 @@
* Comet: http://hakank.org/comet/broken_weights.co
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
import string
@@ -54,90 +55,89 @@ from ortools.constraint_solver import pywrapcp
def main(m=40, n=4):
# Create the solver.
solver = pywrapcp.Solver('Broken weights')
# Create the solver.
solver = pywrapcp.Solver('Broken weights')
#
# data
#
print 'total weight (m):', m
print 'number of pieces (n):', n
#
# data
#
print 'total weight (m):', m
print 'number of pieces (n):', n
print
#
# variables
#
weights = [solver.IntVar(1, m, 'weights[%i]' % j) for j in range(n)]
x = {}
for i in range(m):
for j in range(n):
x[i, j] = solver.IntVar(-1, 1, 'x[%i,%i]' % (i, j))
x_flat = [x[i, j] for i in range(m) for j in range(n)]
#
# constraints
#
# symmetry breaking
for j in range(1, n):
solver.Add(weights[j - 1] < weights[j])
solver.Add(solver.SumEquality(weights, m))
# Check that all weights from 1 to 40 can be made.
#
# Since all weights can be on either side
# of the side of the scale we allow either
# -1, 0, or 1 or the weights, assuming that
# -1 is the weights on the left and 1 is on the right.
#
for i in range(m):
solver.Add(i + 1 == solver.Sum([weights[j] * x[i, j]
for j in range(n)]))
# objective
objective = solver.Minimize(weights[n - 1], 1)
#
# search and result
#
db = solver.Phase(weights + x_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
search_log = solver.SearchLog(1)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'weights: ',
for w in [weights[j].Value() for j in range(n)]:
print '%3i ' % w,
print
#
# variables
#
weights = [solver.IntVar(1, m, 'weights[%i]' % j) for j in range(n)]
x = {}
print '-' * 30
for i in range(m):
for j in range(n):
x[i,j] = solver.IntVar(-1, 1, 'x[%i,%i]' % (i, j))
x_flat = [x[i,j] for i in range(m) for j in range(n)]
#
# constraints
#
# symmetry breaking
for j in range(1, n):
solver.Add(weights[j-1] < weights[j])
solver.Add(solver.SumEquality(weights, m))
# Check that all weights from 1 to 40 can be made.
#
# Since all weights can be on either side
# of the side of the scale we allow either
# -1, 0, or 1 or the weights, assuming that
# -1 is the weights on the left and 1 is on the right.
#
for i in range(m):
solver.Add(i+1 == solver.Sum([weights[j]*x[i,j]
for j in range(n)]))
# objective
objective = solver.Minimize(weights[n-1], 1)
#
# search and result
#
db = solver.Phase(weights + x_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
search_log = solver.SearchLog(1)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'weights: ',
for w in [weights[j].Value() for j in range(n)]:
print '%3i ' % w,
print
print '-' * 30
for i in range(m):
print 'weight %2i:' % (i+1),
for j in range(n):
print '%3i ' % x[i,j].Value(),
print
print
print 'weight %2i:' % (i + 1),
for j in range(n):
print '%3i ' % x[i, j].Value(),
print
print
solver.EndSearch()
print
solver.EndSearch()
print 'num_solutions:', num_solutions
print 'failures :', solver.Failures()
print 'branches :', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures :', solver.Failures()
print 'branches :', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
m = 40
n = 4
if __name__ == '__main__':
if len(sys.argv) > 1:
m = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
main(m, n)
if len(sys.argv) > 1:
m = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
main(m, n)

View File

@@ -30,7 +30,8 @@
* SICStus: http://hakank.org/sicstus/bus_schedule.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -39,78 +40,74 @@ import string
from ortools.constraint_solver import pywrapcp
def main(num_buses_check=0):
# Create the solver.
solver = pywrapcp.Solver('Bus scheduling')
# Create the solver.
solver = pywrapcp.Solver("Bus scheduling")
# data
time_slots = 6
demands = [8, 10, 7, 12, 4, 4]
max_num = sum(demands)
# data
time_slots = 6
demands = [8, 10, 7, 12, 4, 4]
max_num = sum(demands)
# declare variables
x = [solver.IntVar(0, max_num, "x%i"%i) for i in range(time_slots)]
num_buses = solver.IntVar(0, max_num, 'num_buses')
# declare variables
x = [solver.IntVar(0, max_num, "x%i" % i) for i in range(time_slots)]
num_buses = solver.IntVar(0, max_num, "num_buses")
#
# constraints
#
solver.Add(num_buses == solver.Sum(x))
#
# constraints
#
solver.Add(num_buses == solver.Sum(x))
# Meet the demands for this and the next time slot
for i in range(time_slots-1):
solver.Add(x[i]+x[i+1] >= demands[i])
# Meet the demands for this and the next time slot
for i in range(time_slots - 1):
solver.Add(x[i] + x[i + 1] >= demands[i])
# The demand "around the clock"
solver.Add(x[time_slots-1] + x[0] == demands[time_slots-1])
# The demand "around the clock"
solver.Add(x[time_slots - 1] + x[0] == demands[time_slots - 1])
if num_buses_check > 0:
solver.Add(num_buses == num_buses_check)
if num_buses_check > 0:
solver.Add(num_buses == num_buses_check)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num_buses)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num_buses)
collector = solver.AllSolutionCollector(solution)
cargs = [collector]
collector = solver.AllSolutionCollector(solution)
cargs = [collector]
# objective
if num_buses_check == 0:
objective = solver.Minimize(num_buses, 1)
cargs.extend([objective])
# objective
if num_buses_check == 0:
objective = solver.Minimize(num_buses, 1)
cargs.extend([objective])
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
cargs)
num_solutions = collector.SolutionCount()
num_buses_check_value = 0
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))],
num_buses_check_value = collector.Value(s, num_buses)
print " num_buses:", num_buses_check_value
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
if num_buses_check == 0:
return num_buses_check_value
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
cargs)
num_solutions = collector.SolutionCount()
num_buses_check_value = 0
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))],
num_buses_check_value = collector.Value(s, num_buses)
print " num_buses:", num_buses_check_value
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
if num_buses_check == 0:
return num_buses_check_value
if __name__ == '__main__':
print "Check for minimun number of buses"
num_buses_check = main()
print "... got ", num_buses_check, "buses"
print "All solutions:"
main(num_buses_check)
if __name__ == "__main__":
print "Check for minimun number of buses"
num_buses_check = main()
print "... got ", num_buses_check, "buses"
print "All solutions:"
main(num_buses_check)

View File

@@ -26,7 +26,8 @@
* Comet: http://hakank.org/comet/car.co
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -37,112 +38,110 @@ from ortools.constraint_solver import pywrapcp
def main(num_sol=3):
# Create the solver.
solver = pywrapcp.Solver('Car sequence')
# Create the solver.
solver = pywrapcp.Solver("Car sequence")
#
# data
#
nbCars = 6
nbOptions = 5
nbSlots = 10
#
# data
#
nbCars = 6
nbOptions = 5
nbSlots = 10
Cars = range(nbCars)
Options = range(nbOptions)
Slots = range(nbSlots)
Cars = range(nbCars)
Options = range(nbOptions)
Slots = range(nbSlots)
# car 0 1 2 3 4 5
demand = [1, 1, 2, 2, 2, 2]
# car 0 1 2 3 4 5
demand = [1, 1, 2, 2, 2, 2]
option = [
# car 0 1 2 3 4 5
[ 1, 0, 0, 0, 1, 1], # option 1
[ 0, 0, 1, 1, 0, 1], # option 2
[ 1, 0, 0, 0, 1, 0], # option 3
[ 1, 1, 0, 1, 0, 0], # option 4
[ 0, 0, 1, 0, 0, 0] # option 5
]
option = [
# car 0 1 2 3 4 5
[1, 0, 0, 0, 1, 1], # option 1
[0, 0, 1, 1, 0, 1], # option 2
[1, 0, 0, 0, 1, 0], # option 3
[1, 1, 0, 1, 0, 0], # option 4
[0, 0, 1, 0, 0, 0] # option 5
]
capacity = [
(1,2),
(2,3),
(1,3),
(2,5),
(1,5)
]
capacity = [
(1, 2),
(2, 3),
(1, 3),
(2, 5),
(1, 5)
]
optionDemand = [sum([demand[j]*option[i][j] for j in Cars]) \
for i in Options]
optionDemand = [sum([demand[j] * option[i][j] for j in Cars])
for i in Options]
#
# declare variables
#
slot = [solver.IntVar(0, nbCars-1, "slot[%i]" % i) for i in Slots]
setup = {}
for i in Options:
for j in Slots:
setup[(i,j)] = solver.IntVar(0, 1, "setup[%i,%i]" % (i,j))
setup_flat = [setup[i,j] for i in Options for j in Slots]
#
# declare variables
#
slot = [solver.IntVar(0, nbCars - 1, "slot[%i]" % i) for i in Slots]
setup = {}
for i in Options:
for j in Slots:
setup[(i, j)] = solver.IntVar(0, 1, "setup[%i,%i]" % (i, j))
setup_flat = [setup[i, j] for i in Options for j in Slots]
#
# constraints
#
for c in Cars:
b = [solver.IsEqualCstVar(slot[s], c) for s in Slots]
solver.Add(solver.Sum(b) == demand[c])
#
# constraints
#
for c in Cars:
b = [solver.IsEqualCstVar(slot[s], c) for s in Slots]
solver.Add(solver.Sum(b) == demand[c])
for o in Options:
for s in range(0, nbSlots - capacity[o][1] + 1):
b = [setup[o, j] for j in range(s, s + capacity[o][1] - 1)]
solver.Add(solver.Sum(b) <= capacity[o][0])
for o in Options:
for s in Slots:
solver.Add(setup[(o, s)] == solver.Element(option[o], slot[s]))
for o in Options:
for i in range(optionDemand[o]):
s_range = range(0, nbSlots - (i + 1) * capacity[o][1])
ss = [setup[o, s] for s in s_range]
cc = optionDemand[o] - (i + 1) * capacity[o][0]
if len(ss) > 0 and cc >= 0:
solver.Add(solver.Sum(ss) >= cc)
#
# search and result
#
db = solver.Phase(slot + setup_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "slot:%s" % ",".join([str(slot[i].Value()) for i in Slots])
print "setup:"
for o in Options:
for s in range(0, nbSlots-capacity[o][1]+1):
b = [setup[o,j] for j in range(s, s + capacity[o][1]-1)]
solver.Add(solver.Sum(b) <= capacity[o][0])
for o in Options:
for s in Slots:
solver.Add(setup[(o,s)] == solver.Element(option[o], slot[s]))
for o in Options:
for i in range(optionDemand[o]):
s_range = range(0, nbSlots - (i+1) * capacity[o][1])
ss = [setup[o,s] for s in s_range]
cc = optionDemand[o] - (i+1) * capacity[o][0]
if len(ss) > 0 and cc >= 0:
solver.Add(solver.Sum(ss) >= cc)
#
# search and result
#
db = solver.Phase(slot + setup_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "slot:%s" % ",".join([str(slot[i].Value()) for i in Slots])
print "setup:"
for o in Options:
print "%i/%i:" % (capacity[o][0], capacity[o][1]),
for s in Slots:
print setup[o,s].Value(),
print
print
num_solutions += 1
if num_solutions >= num_sol:
break
solver.EndSearch()
print "%i/%i:" % (capacity[o][0], capacity[o][1]),
for s in Slots:
print setup[o, s].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
if num_solutions >= num_sol:
break
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_sol = 3
if __name__ == '__main__':
if len(sys.argv) > 1:
num_sol = string.atoi(sys.argv[1])
main(num_sol)
if __name__ == "__main__":
if len(sys.argv) > 1:
num_sol = string.atoi(sys.argv[1])
main(num_sol)

View File

@@ -37,7 +37,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -52,80 +53,81 @@ from ortools.constraint_solver import pywrapcp
# Note: This assumes that x is has the domain 0..len(x)-1,
# i.e. 0-based.
#
def circuit(solver, x):
n = len(x)
z = [solver.IntVar(0, n-1, 'z%i' % i) for i in range(n)]
n = len(x)
z = [solver.IntVar(0, n - 1, "z%i" % i) for i in range(n)]
solver.Add(solver.AllDifferent(x))
solver.Add(solver.AllDifferent(z))
solver.Add(solver.AllDifferent(x))
solver.Add(solver.AllDifferent(z))
# put the orbit of x[0] in in z[0..n-1]
solver.Add(z[0] == x[0])
for i in range(1,n-1):
# The following constraint give the error
# "TypeError: list indices must be integers, not IntVar"
# solver.Add(z[i] == x[z[i-1]])
# put the orbit of x[0] in in z[0..n-1]
solver.Add(z[0] == x[0])
for i in range(1, n - 1):
# The following constraint give the error
# "TypeError: list indices must be integers, not IntVar"
# solver.Add(z[i] == x[z[i-1]])
# solution: use Element instead
solver.Add(z[i] == solver.Element(x,z[i-1]))
# solution: use Element instead
solver.Add(z[i] == solver.Element(x, z[i - 1]))
#
# Note: At least one of the following two constraint must be set.
#
# may not be 0 for i < n-1
for i in range(1, n-1):
solver.Add(z[i] != 0)
#
# Note: At least one of the following two constraint must be set.
#
# may not be 0 for i < n-1
for i in range(1, n - 1):
solver.Add(z[i] != 0)
# when i = n-1 it must be 0
solver.Add(z[n-1] == 0)
# when i = n-1 it must be 0
solver.Add(z[n - 1] == 0)
def main(n=5):
# Create the solver.
solver = pywrapcp.Solver('Send most money')
# Create the solver.
solver = pywrapcp.Solver("Send most money")
# data
print "n:", n
# data
print "n:", n
# declare variables
# Note: domain should be 0..n-1
x = [solver.IntVar(0,n-1,"x%i"%i) for i in range(n)]
# declare variables
# Note: domain should be 0..n-1
x = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
#
# constraints
#
circuit(solver, x)
#
# constraints
#
circuit(solver, x)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
collector = solver.AllSolutionCollector(solution)
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))]
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
n = 5
if __name__ == '__main__':
if len(sys.argv) > 1:
n=string.atoi(sys.argv[1])
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
main(n)

View File

@@ -34,71 +34,71 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Coins')
# Create the solver.
solver = pywrapcp.Solver("Coins")
#
# data
#
n = 6 # number of different coins
variables = [1, 2, 5, 10, 25, 50]
#
# data
#
n = 6 # number of different coins
variables = [1, 2, 5, 10, 25, 50]
# declare variables
x = [solver.IntVar(0, 99, "x%i" % i) for i in range(n)]
num_coins = solver.IntVar(0, 99, "num_coins")
# declare variables
x = [solver.IntVar(0, 99, 'x%i' % i) for i in range(n)]
num_coins = solver.IntVar(0, 99, 'num_coins')
#
# constraints
#
#
# constraints
#
# number of used coins, to be minimized
solver.Add(num_coins == solver.Sum(x))
# number of used coins, to be minimized
solver.Add(num_coins == solver.Sum(x))
# Check that all changes from 1 to 99 can be made.
for j in range(1, 100):
tmp = [solver.IntVar(0, 99, "b%i" % i) for i in range(n)]
solver.Add(solver.ScalProd(tmp, variables) == j)
[solver.Add(tmp[i] <= x[i]) for i in range(n)]
# Check that all changes from 1 to 99 can be made.
for j in range(1, 100):
tmp = [solver.IntVar(0, 99, 'b%i'%i) for i in range(n)]
solver.Add(solver.ScalProd(tmp, variables) == j)
[solver.Add(tmp[i] <= x[i]) for i in range(n)]
# objective
objective = solver.Minimize(num_coins, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num_coins)
solution.AddObjective(num_coins)
# objective
objective = solver.Minimize(num_coins, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num_coins)
solution.AddObjective(num_coins)
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "x: ", [x[i].Value() for i in range(n)]
print "num_coins:", num_coins.Value()
print
num_solutions += 1
solver.EndSearch()
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "x: ", [x[i].Value() for i in range(n)]
print "num_coins:", num_coins.Value()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -50,24 +50,26 @@
* JaCoP: http://hakank.org/JaCoP/CoinsGrid.java
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main(unused_argv):
# Create the solver.
solver = pywrapcp.Solver('Coins grid')
solver = pywrapcp.Solver("Coins grid")
# data
n = 31 # the grid size
c = 14 # number of coins per row/column
# data
n = 31 # the grid size
c = 14 # number of coins per row/column
# (6, 4)
# declare variables
# declare variables
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = solver.BoolVar('x %i %i' % (i, j))
x[(i, j)] = solver.BoolVar("x %i %i" % (i, j))
#
# constraints
@@ -75,8 +77,8 @@ def main(unused_argv):
# sum rows/columns == c
for i in range(n):
solver.Add(solver.SumEquality([x[(i, j)] for j in range(n)], c)) # sum rows
solver.Add(solver.SumEquality([x[(j, i)] for j in range(n)], c)) # sum cols
solver.Add(solver.SumEquality([x[(i, j)] for j in range(n)], c)) # sum rows
solver.Add(solver.SumEquality([x[(j, i)] for j in range(n)], c)) # sum cols
# quadratic horizonal distance var
objective_var = solver.Sum([x[(i, j)] * (i - j) * (i - j)
@@ -89,14 +91,14 @@ def main(unused_argv):
# solution and search
#
solution = solver.Assignment()
solution.Add([x[(i,j)] for i in range(n) for j in range(n)])
solution.Add([x[(i, j)] for i in range(n) for j in range(n)])
solution.AddObjective(objective_var)
# last solutions
collector = solver.LastSolutionCollector(solution)
search_log = solver.SearchLog(1000000, objective_var)
restart = solver.ConstantRestart(300)
solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)],
solver.Solve(solver.Phase([x[(i, j)] for i in range(n) for j in range(n)],
solver.CHOOSE_RANDOM,
solver.ASSIGN_MAX_VALUE),
[collector, search_log, objective])
@@ -113,5 +115,5 @@ def main(unused_argv):
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main("coin grids")
if __name__ == "__main__":
main("coin grids")

View File

@@ -37,33 +37,34 @@
and use
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.linear_solver import pywraplp
def main(unused_argv):
# Create the solver.
# using GLPK
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
# Using CLP
# solver = pywraplp.Solver('CoinsGridCLP',
# pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# data
n = 31 # the grid size
c = 14 # number of coins per row/column
n = 31 # the grid size
c = 14 # number of coins per row/column
# declare variables
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
x[(i, j)] = solver.IntVar(0, 1, 'x[%i,%i]' % (i, j))
#
# constraints
@@ -72,14 +73,14 @@ def main(unused_argv):
# sum rows/columns == c
for i in range(n):
solver.Add(solver.Sum(
[x[(i, j)] for j in range(n)]) == c) # sum rows
[x[(i, j)] for j in range(n)]) == c) # sum rows
solver.Add(solver.Sum(
[x[(j, i)] for j in range(n)]) == c) # sum cols
[x[(j, i)] for j in range(n)]) == c) # sum cols
# quadratic horizonal distance var
objective_var = solver.Sum(
[x[(i, j)] * (i - j) * (i - j)
for i in range(n) for j in range(n)])
[x[(i, j)] * (i - j) * (i - j)
for i in range(n) for j in range(n)])
# objective
objective = solver.Minimize(objective_var)
@@ -102,4 +103,4 @@ def main(unused_argv):
if __name__ == '__main__':
main("coin grids")
main('coin grids')

View File

@@ -34,14 +34,15 @@
http://www.hakank.org/minizinc/coloring_ip.mzn
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -53,8 +54,8 @@ def main(sol = 'GLPK'):
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CBC
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
@@ -78,27 +79,26 @@ def main(sol = 'GLPK'):
# http://mat.gsia.cmu.edu/COLOR/instances.html
#
# Note: 1-based (adjusted below)
E = [[1, 2],
[1, 4],
[1, 7],
[1, 9],
[2, 3],
[2, 6],
[2, 8],
[3, 5],
[3, 7],
[3, 10],
[4, 5],
[4, 6],
[4, 10],
[5, 8],
[5, 9],
[6, 11],
[7, 11],
[8, 11],
[9, 11],
[10, 11]]
E = [[1, 2],
[1, 4],
[1, 7],
[1, 9],
[2, 3],
[2, 6],
[2, 8],
[3, 5],
[3, 7],
[3, 10],
[4, 5],
[4, 6],
[4, 10],
[5, 8],
[5, 9],
[6, 11],
[7, 11],
[8, 11],
[9, 11],
[10, 11]]
#
# declare variables
@@ -108,8 +108,7 @@ def main(sol = 'GLPK'):
x = {}
for v in V:
for j in range(nc):
x[v,j] = solver.IntVar(0, 1, 'v[%i,%i]' % (v, j))
x[v, j] = solver.IntVar(0, 1, 'v[%i,%i]' % (v, j))
# u[c] = 1 means that color c is used, i.e. assigned to some node
u = [solver.IntVar(0, 1, 'u[%i]' % i) for i in range(nc)]
@@ -117,22 +116,19 @@ def main(sol = 'GLPK'):
# number of colors used, to minimize
obj = solver.Sum(u)
#
# constraints
#
# each node must be assigned exactly one color
for i in V:
solver.Add(solver.Sum([x[i,c] for c in range(nc)]) == 1)
solver.Add(solver.Sum([x[i, c] for c in range(nc)]) == 1)
# adjacent nodes cannot be assigned the same color
# (and adjust to 0-based)
for i in range(num_edges):
for c in range(nc):
solver.Add(x[E[i][0]-1,c] + x[E[i][1]-1,c] <= u[c])
for c in range(nc):
solver.Add(x[E[i][0] - 1, c] + x[E[i][1] - 1, c] <= u[c])
# objective
objective = solver.Minimize(obj)
@@ -143,23 +139,22 @@ def main(sol = 'GLPK'):
solver.Solve()
print
print "number of colors:", int(solver.Objective().Value())
print "colors used:", [int(u[i].SolutionValue()) for i in range(nc)]
print 'number of colors:', int(solver.Objective().Value())
print 'colors used:', [int(u[i].SolutionValue()) for i in range(nc)]
print
for v in V:
print 'v%i' % v, ' color ',
for c in range(nc):
if int(x[v,c].SolutionValue()) == 1:
if int(x[v, c].SolutionValue()) == 1:
print c
print
print "WallTime:", solver.WallTime()
print 'WallTime:', solver.WallTime()
if sol == 'CBC':
print 'iterations:', solver.Iterations()
if __name__ == '__main__':
sol = 'GLPK'

View File

@@ -28,84 +28,85 @@
* Gecode: http://hakank.org/gecode/combinatorial_auction.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys,string
import sys
import string
from collections import *
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Problem')
# Create the solver.
solver = pywrapcp.Solver("Problem")
#
# data
#
N = 5
#
# data
#
N = 5
# the items for each bid
items = [
[0,1], # A,B
[0,2], # A, C
[1,3], # B,D
[1,2,3], # B,C,D
[0] # A
]
# collect the bids for each item
items_t = defaultdict(list)
# the items for each bid
items = [
[0, 1], # A,B
[0, 2], # A, C
[1, 3], # B,D
[1, 2, 3], # B,C,D
[0] # A
]
# collect the bids for each item
items_t = defaultdict(list)
# [items_t.setdefault(j,[]).append(i) for i in range(N) for j in items[i] ]
# nicer:
[items_t[j].append(i) for i in range(N) for j in items[i] ]
# [items_t.setdefault(j,[]).append(i) for i in range(N) for j in items[i] ]
# nicer:
[items_t[j].append(i) for i in range(N) for j in items[i]]
bid_amount = [10,20,30,40,14]
bid_amount = [10, 20, 30, 40, 14]
#
# declare variables
#
X = [solver.BoolVar("x%i"%i) for i in range(N)]
obj = solver.IntVar(0,100,'obj')
#
# declare variables
#
X = [solver.BoolVar("x%i" % i) for i in range(N)]
obj = solver.IntVar(0, 100, "obj")
#
# constraints
#
solver.Add(obj == solver.ScalProd(X,bid_amount))
for item in items_t:
solver.Add(solver.Sum([X[bid] for bid in items_t[item]]) <= 1)
#
# constraints
#
solver.Add(obj == solver.ScalProd(X, bid_amount))
for item in items_t:
solver.Add(solver.Sum([X[bid] for bid in items_t[item]]) <= 1)
# objective
objective = solver.Maximize(obj, 1)
# objective
objective = solver.Maximize(obj, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(X)
solution.Add(obj)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(X)
solution.Add(obj)
# db: DecisionBuilder
db = solver.Phase(X,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db,[objective])
num_solutions = 0
while solver.NextSolution():
print "X:", [X[i].Value() for i in range(N)]
print "obj:", obj.Value()
print
num_solutions += 1
solver.EndSearch()
# db: DecisionBuilder
db = solver.Phase(X,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "X:", [X[i].Value() for i in range(N)]
print "obj:", obj.Value()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
if __name__ == '__main__':
main()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == "__main__":
main()

View File

@@ -1,16 +1,16 @@
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
@@ -22,22 +22,23 @@
From Global Constraint Catalogue
http://www.emn.fr/x-info/sdemasse/gccat/Cglobal_contiguity.html
'''
Enforce all variables of the VARIABLES collection to be assigned to 0 or 1.
Enforce all variables of the VARIABLES collection to be assigned to 0 or 1.
In addition, all variables assigned to value 1 appear contiguously.
Example:
(<0, 1, 1, 0>)
The global_contiguity constraint holds since the sequence 0 1 1 0 contains
The global_contiguity constraint holds since the sequence 0 1 1 0 contains
no more than one group of contiguous 1.
'''
Compare with the following model:
* MiniZinc: http://www.hakank.org/minizinc/contiguity_regular.mzn
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -45,7 +46,7 @@ from ortools.constraint_solver import pywrapcp
#
# Global constraint regular
#
# This is a translation of MiniZinc's regular constraint (defined in
# This is a translation of MiniZinc's regular constraint (defined in
# lib/zinc/globals.mzn), via the Comet code refered above.
# All comments are from the MiniZinc code.
# '''
@@ -62,116 +63,116 @@ from ortools.constraint_solver import pywrapcp
# d : transition matrix
# q0: initial state
# F : accepting states
def regular(x, Q, S, d, q0, F):
solver = x[0].solver()
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
solver = x[0].solver()
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q+1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i-1][j])
d2.append(row)
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)]
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1)))
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q + 1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i - 1][j])
d2.append(row)
d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(
a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))
def main():
# Create the solver.
solver = pywrapcp.Solver('Global contiguity using regular')
#
# data
#
# the DFA (for regular)
n_states = 3
input_max = 2
initial_state = 1 # 0 is for the failing state
# all states are accepting states
accepting_states = [1,2,3]
# Create the solver.
solver = pywrapcp.Solver('Global contiguity using regular')
# The regular expression 0*1*0*
transition_fn = [
[1,2], # state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0*
[3,2], # state 2: 1*
[3,0], # state 3: 0*
]
#
# data
#
# the DFA (for regular)
n_states = 3
input_max = 2
initial_state = 1 # 0 is for the failing state
n = 7
# all states are accepting states
accepting_states = [1, 2, 3]
#
# declare variables
#
# The regular expression 0*1*0*
transition_fn = [
[1, 2], # state 1 (start): input 0 -> state 1, input 1 -> state 2 i.e. 0*
[3, 2], # state 2: 1*
[3, 0], # state 3: 0*
]
# We use 1..2 and subtract 1 in the solution
reg_input = [solver.IntVar(1, 2, 'x[%i]'% i) for i in range(n)]
n = 7
#
# declare variables
#
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
# We use 1..2 and subtract 1 in the solution
reg_input = [solver.IntVar(1, 2, 'x[%i]' % i) for i in range(n)]
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
# Note: here we subract 1 from the solution
print 'reg_input:', [reg_input[i].Value()-1 for i in range(n)]
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'wall_time:', solver.WallTime(), 'ms'
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
# Note: here we subract 1 from the solution
print 'reg_input:', [reg_input[i].Value() - 1 for i in range(n)]
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'wall_time:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -41,10 +41,10 @@
the array, e.g. those listed in
http://mathworld.wolfram.com/CostasArray.html
1 1 (1)
2 2 (1, 2), (2,1)
3 4 (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2)
4 12 (1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4),
1 1 (1)
2 2 (1, 2), (2,1)
3 4 (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2)
4 12 (1, 2, 4, 3), (1, 3, 4, 2), (1, 4, 2, 3), (2, 1, 3, 4),
(2, 3, 1, 4), (2, 4, 3, 1), (3, 1, 2, 4), (3, 2, 4, 1),
(3, 4, 2, 1), (4, 1, 3, 2), (4, 2, 1, 3), (4, 3, 1, 2)
....
@@ -57,7 +57,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
import string
@@ -67,109 +68,105 @@ from ortools.constraint_solver import pywrapcp
def main(n=6):
# Create the solver.
solver = pywrapcp.Solver('Costas array')
# Create the solver.
solver = pywrapcp.Solver("Costas array")
#
# data
#
print "n:", n
#
# data
#
print "n:", n
#
# declare variables
#
costas = [solver.IntVar(1, n, "costas[%i]"%i) for i in range(n)]
differences = {}
#
# declare variables
#
costas = [solver.IntVar(1, n, "costas[%i]" % i) for i in range(n)]
differences = {}
for i in range(n):
for j in range(n):
differences[(i, j)] = solver.IntVar(-n + 1, n - 1,
"differences[%i,%i]" % (i, j))
differences_flat = [differences[i, j] for i in range(n) for j in range(n)]
#
# constraints
#
# Fix the values in the lower triangle in the
# difference matrix to -n+1. This removes variants
# of the difference matrix for the the same Costas array.
for i in range(n):
for j in range(i + 1):
solver.Add(differences[i, j] == -n + 1)
# hakank: All the following constraints are from
# Barry O'Sullivans's original model.
#
solver.Add(solver.AllDifferent(costas))
# "How do the positions in the Costas array relate
# to the elements of the distance triangle."
for i in range(n):
for j in range(n):
if i < j:
solver.Add(differences[(i, j)] == costas[j] - costas[j - i - 1])
# "All entries in a particular row of the difference
# triangle must be distint."
for i in range(n - 2):
solver.Add(solver.AllDifferent([differences[i, j]
for j in range(n) if j > i]))
#
# "All the following are redundant - only here to speed up search."
#
# "We can never place a 'token' in the same row as any other."
for i in range(n):
for j in range(n):
if i < j:
solver.Add(differences[i, j] != 0)
for k in range(2, n):
for l in range(2, n):
if k < l:
solver.Add(differences[k - 2, l - 1] +
differences[k, l] ==
differences[k - 1, l - 1] +
differences[k - 1, l])
#
# search and result
#
db = solver.Phase(costas + differences_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "costas:", [costas[i].Value() for i in range(n)]
print "differences:"
for i in range(n):
for j in range(n):
differences[(i,j)] = solver.IntVar(-n+1, n-1,
"differences[%i,%i]"%(i,j))
differences_flat = [differences[i,j] for i in range(n) for j in range(n) ]
#
# constraints
#
# Fix the values in the lower triangle in the
# difference matrix to -n+1. This removes variants
# of the difference matrix for the the same Costas array.
for i in range(n):
for j in range(i+1):
solver.Add(differences[i,j] == -n+1)
# hakank: All the following constraints are from
# Barry O'Sullivans's original model.
#
solver.Add(solver.AllDifferent(costas))
# "How do the positions in the Costas array relate
# to the elements of the distance triangle."
for i in range(n):
for j in range(n):
if i < j:
solver.Add(differences[(i,j)] == costas[j] - costas[j-i-1])
# "All entries in a particular row of the difference
# triangle must be distint."
for i in range(n-2):
solver.Add(solver.AllDifferent([differences[i,j]
for j in range(n) if j > i]))
#
# "All the following are redundant - only here to speed up search."
#
# "We can never place a 'token' in the same row as any other."
for i in range(n):
for j in range(n):
if i < j:
solver.Add(differences[i,j] != 0)
for k in range(2,n):
for l in range(2, n):
if k < l:
solver.Add(differences[k-2,l-1] +
differences[k,l] ==
differences[k-1,l-1] +
differences[k-1,l])
#
# search and result
#
db = solver.Phase(costas + differences_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "costas:", [costas[i].Value() for i in range(n)]
print "differences:"
for i in range(n):
for j in range(n):
v = differences[i,j].Value()
if v == -n+1:
print " ",
else:
print "%2d" % v,
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
v = differences[i, j].Value()
if v == -n + 1:
print " ",
else:
print "%2d" % v,
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
n = 6
if __name__ == '__main__':
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)

View File

@@ -53,7 +53,8 @@
* SICStus: http://hakank.org/sicstus/covering_opl.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -64,91 +65,89 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Set covering')
# Create the solver.
solver = pywrapcp.Solver("Set covering")
#
# data
#
nb_workers = 32
Workers = range(nb_workers)
num_tasks = 15
Tasks = range(num_tasks)
#
# data
#
nb_workers = 32
Workers = range(nb_workers)
num_tasks = 15
Tasks = range(num_tasks)
# Which worker is qualified for each task.
# Note: This is 1-based and will be made 0-base below.
Qualified = [
[ 1, 9, 19, 22, 25, 28, 31 ],
[ 2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32 ],
[ 3, 10, 19, 24, 26, 30, 32 ],
[ 4, 21, 25, 28, 32 ],
[ 5, 11, 16, 22, 23, 27, 31 ],
[ 6, 20, 24, 26, 30, 32 ],
[ 7, 12, 17, 25, 30, 31 ] ,
[ 8, 17, 20, 22, 23 ],
[ 9, 13, 14, 26, 29, 30, 31 ],
[ 10, 21, 25, 31, 32 ],
[ 14, 15, 18, 23, 24, 27, 30, 32 ],
[ 18, 19, 22, 24, 26, 29, 31 ],
[ 11, 20, 25, 28, 30, 32 ],
[ 16, 19, 23, 31 ],
[ 9, 18, 26, 28, 31, 32 ]
]
# Which worker is qualified for each task.
# Note: This is 1-based and will be made 0-base below.
Qualified = [
[1, 9, 19, 22, 25, 28, 31],
[2, 12, 15, 19, 21, 23, 27, 29, 30, 31, 32],
[3, 10, 19, 24, 26, 30, 32],
[4, 21, 25, 28, 32],
[5, 11, 16, 22, 23, 27, 31],
[6, 20, 24, 26, 30, 32],
[7, 12, 17, 25, 30, 31],
[8, 17, 20, 22, 23],
[9, 13, 14, 26, 29, 30, 31],
[10, 21, 25, 31, 32],
[14, 15, 18, 23, 24, 27, 30, 32],
[18, 19, 22, 24, 26, 29, 31],
[11, 20, 25, 28, 30, 32],
[16, 19, 23, 31],
[9, 18, 26, 28, 31, 32]
]
Cost = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 8, 9 ]
Cost = [
1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5,
5, 5, 6, 6, 6, 7, 8, 9]
#
# variables
#
Hire = [solver.IntVar(0, 1, "Hire[%i]" % w) for w in Workers]
total_cost = solver.IntVar(0, nb_workers * sum(Cost), "total_cost")
#
# variables
#
Hire = [solver.IntVar(0, 1, 'Hire[%i]' % w) for w in Workers]
total_cost = solver.IntVar(0, nb_workers*sum(Cost), 'total_cost')
#
# constraints
#
solver.Add(total_cost == solver.ScalProd(Hire, Cost))
#
# constraints
#
solver.Add(total_cost == solver.ScalProd(Hire, Cost))
for j in Tasks:
# Sum the cost for hiring the qualified workers
# (also, make 0-base)
b = solver.Sum([Hire[c - 1] for c in Qualified[j]])
solver.Add(b >= 1)
for j in Tasks:
# Sum the cost for hiring the qualified workers
# (also, make 0-base)
b = solver.Sum([Hire[c-1] for c in Qualified[j]])
solver.Add(b >= 1)
# objective: Minimize total cost
objective = solver.Minimize(total_cost, 1)
#
# search and result
#
db = solver.Phase(Hire,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
# objective: Minimize total cost
objective = solver.Minimize(total_cost, 1)
#
# search and result
#
db = solver.Phase(Hire,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Total cost", total_cost.Value()
print "We should hire these workers: ",
for w in Workers:
if Hire[w].Value() == 1:
print w,
print
print
solver.EndSearch()
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Total cost", total_cost.Value()
print "We should hire these workers: ",
for w in Workers:
if Hire[w].Value() == 1:
print w,
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -35,190 +35,190 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
def main(sols=1):
# Create the solver.
solver = pywrapcp.Solver('Crew')
# Create the solver.
solver = pywrapcp.Solver("Crew")
#
# data
#
names = ["Tom",
"David",
"Jeremy",
"Ron",
"Joe",
"Bill",
"Fred",
"Bob",
"Mario",
"Ed",
"Carol",
"Janet",
"Tracy",
"Marilyn",
"Carolyn",
"Cathy",
"Inez",
"Jean",
"Heather",
"Juliet"
]
#
# data
#
names = ["Tom",
"David",
"Jeremy",
"Ron",
"Joe",
"Bill",
"Fred",
"Bob",
"Mario",
"Ed",
"Carol",
"Janet",
"Tracy",
"Marilyn",
"Carolyn",
"Cathy",
"Inez",
"Jean",
"Heather",
"Juliet"]
num_persons = len(names) # number of persons
num_persons = len(names) # number of persons
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
[1,0,0,0,0], # Bob = 8
[1,0,0,1,1], # Mario = 9
[1,0,0,0,0], # Ed = 10
[0,1,0,0,0], # Carol = 11
[0,1,0,0,0], # Janet = 12
[0,1,0,0,0], # Tracy = 13
[0,1,0,1,1], # Marilyn = 14
[0,1,0,0,0], # Carolyn = 15
[0,1,0,0,0], # Cathy = 16
[0,1,1,1,1], # Inez = 17
[0,1,1,0,0], # Jean = 18
[0,1,0,1,1], # Heather = 19
[0,1,1,0,0] # Juliet = 20
]
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
[1, 0, 0, 0, 0], # Bob = 8
[1, 0, 0, 1, 1], # Mario = 9
[1, 0, 0, 0, 0], # Ed = 10
[0, 1, 0, 0, 0], # Carol = 11
[0, 1, 0, 0, 0], # Janet = 12
[0, 1, 0, 0, 0], # Tracy = 13
[0, 1, 0, 1, 1], # Marilyn = 14
[0, 1, 0, 0, 0], # Carolyn = 15
[0, 1, 0, 0, 0], # Cathy = 16
[0, 1, 1, 1, 1], # Inez = 17
[0, 1, 1, 0, 0], # Jean = 18
[0, 1, 0, 1, 1], # Heather = 19
[0, 1, 1, 0, 0] # Juliet = 20
]
# The columns are in the following order:
# staff : Overall number of cabin crew needed
# stewards : How many stewards are required
# hostesses : How many hostesses are required
# french : How many French speaking employees are required
# spanish : How many Spanish speaking employees are required
# german : How many German speaking employees are required
required_crew = [
[4,1,1,1,1,1], # Flight 1
[5,1,1,1,1,1], # Flight 2
[5,1,1,1,1,1], # ..
[6,2,2,1,1,1],
[7,3,3,1,1,1],
[4,1,1,1,1,1],
[5,1,1,1,1,1],
[6,1,1,1,1,1],
[6,2,2,1,1,1], # ...
[7,3,3,1,1,1] # Flight 10
]
# The columns are in the following order:
# staff : Overall number of cabin crew needed
# stewards : How many stewards are required
# hostesses : How many hostesses are required
# french : How many French speaking employees are required
# spanish : How many Spanish speaking employees are required
# german : How many German speaking employees are required
required_crew = [
[4, 1, 1, 1, 1, 1], # Flight 1
[5, 1, 1, 1, 1, 1], # Flight 2
[5, 1, 1, 1, 1, 1], # ..
[6, 2, 2, 1, 1, 1],
[7, 3, 3, 1, 1, 1],
[4, 1, 1, 1, 1, 1],
[5, 1, 1, 1, 1, 1],
[6, 1, 1, 1, 1, 1],
[6, 2, 2, 1, 1, 1], # ...
[7, 3, 3, 1, 1, 1] # Flight 10
]
num_flights = len(required_crew) # number of flights
num_flights = len(required_crew) # number of flights
#
# declare variables
#
crew = {}
#
# declare variables
#
crew = {}
for i in range(num_flights):
for j in range(num_persons):
crew[(i, j)] = solver.IntVar(0, 1, "crew[%i,%i]" % (i, j))
crew_flat = [crew[(i, j)] for i in range(num_flights)
for j in range(num_persons)]
# number of working persons
num_working = solver.IntVar(1, num_persons, "num_working")
#
# constraints
#
# number of working persons
solver.Add(num_working == solver.Sum(
[solver.IsGreaterOrEqualCstVar(solver.Sum([crew[(f, p)]
for f in range(num_flights)]), 1)
for p in range(num_persons)]))
for f in range(num_flights):
# size of crew
tmp = [crew[(f, i)] for i in range(num_persons)]
solver.Add(solver.Sum(tmp) == required_crew[f][0])
# attributes and requirements
for j in range(5):
tmp = [attributes[i][j] * crew[(f, i)] for i in range(num_persons)]
solver.Add(solver.Sum(tmp) >= required_crew[f][j + 1])
# after a flight, break for at least two flights
for f in range(num_flights - 2):
for i in range(num_persons):
solver.Add(crew[f, i] + crew[f + 1, i] + crew[f + 2, i] <= 1)
# extra contraint: all must work at least two of the flights
# for i in range(num_persons):
# [solver.Add(solver.Sum([crew[f,i] for f in range(num_flights)]) >= 2) ]
#
# solution and search
#
solution = solver.Assignment()
solution.Add(crew_flat)
solution.Add(num_working)
db = solver.Phase(crew_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Solution #%i" % num_solutions
print "Number working:", num_working.Value()
for i in range(num_flights):
for j in range(num_persons):
crew[(i,j)] = solver.IntVar(0, 1, 'crew[%i,%i]' % (i, j))
crew_flat = [crew[(i,j)] for i in range(num_flights) for j in range(num_persons)]
# number of working persons
num_working = solver.IntVar(1, num_persons, 'num_working')
#
# constraints
#
# number of working persons
solver.Add(num_working == solver.Sum(
[solver.IsGreaterOrEqualCstVar(solver.Sum([crew[(f,p)]
for f in range(num_flights)]), 1)
for p in range(num_persons) ]) )
for f in range(num_flights):
# size of crew
tmp = [crew[(f,i)] for i in range(num_persons)]
solver.Add(solver.Sum(tmp) == required_crew[f][0])
# attributes and requirements
for j in range(5):
tmp = [attributes[i][j]*crew[(f,i)] for i in range(num_persons) ]
solver.Add(solver.Sum(tmp) >= required_crew[f][j+1])
# after a flight, break for at least two flights
for f in range(num_flights-2):
for i in range(num_persons):
solver.Add(crew[f,i] + crew[f+1,i] + crew[f+2,i] <= 1)
# extra contraint: all must work at least two of the flights
# for i in range(num_persons):
# [solver.Add(solver.Sum([crew[f,i] for f in range(num_flights)]) >= 2) ]
#
# solution and search
#
solution = solver.Assignment()
solution.Add(crew_flat)
solution.Add(num_working)
db = solver.Phase(crew_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Solution #%i" % num_solutions
print "Number working:", num_working.Value()
for i in range(num_flights):
for j in range(num_persons):
print crew[i,j].Value(),
print
print
print "Flights:"
for flight in range(num_flights):
print "Flight", flight, "persons:",
for person in range(num_persons):
if crew[flight, person].Value() == 1:
print names[person],
print
print
print "Crew:"
for person in range(num_persons):
print "%-10s flights" % names[person],
for flight in range(num_flights):
if crew[flight, person].Value() == 1:
print flight,
print
print
if num_solutions >= sols:
break
solver.EndSearch()
for j in range(num_persons):
print crew[i, j].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "Flights:"
for flight in range(num_flights):
print "Flight", flight, "persons:",
for person in range(num_persons):
if crew[flight, person].Value() == 1:
print names[person],
print
print
print "Crew:"
for person in range(num_persons):
print "%-10s flights" % names[person],
for flight in range(num_flights):
if crew[flight, person].Value() == 1:
print flight,
print
print
if num_solutions >= sols:
break
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions_to_show = 1
if __name__ == '__main__':
if (len(sys.argv) > 1):
num_solutions_to_show = string.atoi(sys.argv[1])
if __name__ == "__main__":
if (len(sys.argv) > 1):
num_solutions_to_show = string.atoi(sys.argv[1])
main(num_solutions_to_show)
main(num_solutions_to_show)

View File

@@ -39,7 +39,8 @@
that will start at those locations.
'''
The model was inspired by Sebastian Brand's Array Constraint cross word example
The model was inspired by Sebastian Brand's Array Constraint cross word
example
http://www.cs.mu.oz.au/~sbrand/project/ac/
http://www.cs.mu.oz.au/~sbrand/project/ac/examples.pl
@@ -53,7 +54,8 @@
* Zinc: http://hakank.org/minizinc/crossword2.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from google.apputils import app
@@ -61,121 +63,141 @@ from ortools.constraint_solver import pywrapcp
def main(_):
# Create the solver.
solver = pywrapcp.Solver('Problem')
# Create the solver.
solver = pywrapcp.Solver("Problem")
#
# data
#
alpha = "_abcdefghijklmnopqrstuvwxyz";
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;
#
# data
#
alpha = "_abcdefghijklmnopqrstuvwxyz"
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
num_words = 15
word_len = 5;
AA = [
[h, o, s, e, s], # HOSES
[l, a, s, e, r], # LASER
[s, a, i, l, s], # SAILS
[s, h, e, e, t], # SHEET
[s, t, e, e, r], # STEER
[h, e, e, l, 0], # HEEL
[h, i, k, e, 0], # HIKE
[k, e, e, l, 0], # KEEL
[k, n, o, t, 0], # KNOT
[l, i, n, e, 0], # LINE
[a, f, t, 0, 0], # AFT
[a, l, e, 0, 0], # ALE
[e, e, l, 0, 0], # EEL
[l, e, e, 0, 0], # LEE
[t, i, e, 0, 0] # TIE
]
num_words = 15
word_len = 5
AA = [
[h, o, s, e, s], # HOSES
[l, a, s, e, r], # LASER
[s, a, i, l, s], # SAILS
[s, h, e, e, t], # SHEET
[s, t, e, e, r], # STEER
[h, e, e, l, 0], # HEEL
[h, i, k, e, 0], # HIKE
[k, e, e, l, 0], # KEEL
[k, n, o, t, 0], # KNOT
[l, i, n, e, 0], # LINE
[a, f, t, 0, 0], # AFT
[a, l, e, 0, 0], # ALE
[e, e, l, 0, 0], # EEL
[l, e, e, 0, 0], # LEE
[t, i, e, 0, 0] # TIE
]
num_overlapping = 12
overlapping = [
[0, 2, 1, 0], # s
[0, 4, 2, 0], # s
num_overlapping = 12
overlapping = [
[0, 2, 1, 0], # s
[0, 4, 2, 0], # s
[3, 1, 1, 2], # i
[3, 2, 4, 0], # k
[3, 3, 2, 2], # e
[3, 1, 1, 2], # i
[3, 2, 4, 0], # k
[3, 3, 2, 2], # e
[6, 0, 1, 3], # l
[6, 1, 4, 1], # e
[6, 2, 2, 3], # e
[6, 0, 1, 3], # l
[6, 1, 4, 1], # e
[6, 2, 2, 3], # e
[7, 0, 5, 1], # l
[7, 2, 1, 4], # s
[7, 3, 4, 2], # e
[7, 4, 2, 4] # r
]
[7, 0, 5, 1], # l
[7, 2, 1, 4], # s
[7, 3, 4, 2], # e
[7, 4, 2, 4] # r
]
n = 8
n = 8
# declare variables
A = {}
for I in range(num_words):
for J in range(word_len):
A[(I,J)] = solver.IntVar(0,26, 'A(%i,%i)' % (I, J))
# declare variables
A = {}
for I in range(num_words):
for J in range(word_len):
A[(I, J)] = solver.IntVar(0, 26, "A(%i,%i)" % (I, J))
A_flat = [A[(I,J)] for I in range(num_words) for J in range(word_len)]
E = [solver.IntVar(0, num_words, "E%i"%I) for I in range(n)]
A_flat = [A[(I, J)] for I in range(num_words) for J in range(word_len)]
E = [solver.IntVar(0, num_words, "E%i" % I) for I in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(E))
#
# constraints
#
solver.Add(solver.AllDifferent(E))
for I in range(num_words):
for J in range(word_len):
solver.Add(A[(I, J)] == AA[I][J])
for I in range(num_words):
for J in range(word_len):
solver.Add(A[(I,J)] == AA[I][J])
for I in range(num_overlapping):
# This is what I would do:
# solver.Add(A[(E[overlapping[I][0]], overlapping[I][1])] == A[(E[overlapping[I][2]], overlapping[I][3])])
for I in range(num_overlapping):
# This is what I would do:
# solver.Add(A[(E[overlapping[I][0]], overlapping[I][1])] == A[(E[overlapping[I][2]], overlapping[I][3])])
# But we must use Element explicitly
solver.Add(
solver.Element(
A_flat, E[overlapping[I][0]] * word_len + overlapping[I][1]) ==
solver.Element(
A_flat, E[overlapping[I][2]] * word_len + overlapping[I][3]))
# But we must use Element explicitly
solver.Add(
solver.Element(A_flat,E[overlapping[I][0]]*word_len+overlapping[I][1])
==
solver.Element(A_flat,E[overlapping[I][2]]*word_len+overlapping[I][3]))
#
# solution and search
#
solution = solver.Assignment()
solution.Add(E)
# db: DecisionBuilder
db = solver.Phase(E + A_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(E)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print E
print_solution(A, E, alpha, n, word_len)
num_solutions += 1
solver.EndSearch()
# db: DecisionBuilder
db = solver.Phase(E + A_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print E
print_solution(A,E,alpha, n, word_len)
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
def print_solution(A, E, alpha, n, word_len):
for ee in range(n):
print "%i: (%2i)" % (ee,E[ee].Value()),
print "".join(["%s" % (alpha[A[ee,ii].Value()]) for ii in range(word_len)])
for ee in range(n):
print "%i: (%2i)" % (ee, E[ee].Value()),
print "".join(["%s" % (alpha[A[ee, ii].Value()]) for ii in range(word_len)])
if __name__ == '__main__':
if __name__ == "__main__":
app.run()

View File

@@ -41,7 +41,8 @@
* SICStus: http://hakank.org/sicstus/crypta.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -49,71 +50,67 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Crypta')
# Create the solver.
solver = pywrapcp.Solver("Crypta")
#
# data
#
#
# data
#
#
# variables
#
LD = [solver.IntVar(0, 9, 'LD[%i]' % i) for i in range(0,10)]
A,B,C,D,E,F,G,H,I,J = LD
#
# variables
#
LD = [solver.IntVar(0, 9, "LD[%i]" % i) for i in range(0, 10)]
A, B, C, D, E, F, G, H, I, J = LD
Sr1 = solver.IntVar(0, 1, 'Sr1')
Sr2 = solver.IntVar(0, 1, 'Sr2')
Sr1 = solver.IntVar(0, 1, "Sr1")
Sr2 = solver.IntVar(0, 1, "Sr2")
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
solver.Add(B >= 1)
solver.Add(D >= 1)
solver.Add(G >= 1)
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
solver.Add(B >= 1)
solver.Add(D >= 1)
solver.Add(G >= 1)
solver.Add(A+10*E+100*J+1000*B+10000*B+100000*E+1000000*F+
E+10*J+100*E+1000*F+10000*G+100000*A+1000000*F
== F+10*E+100*E+1000*H+10000*I+100000*F+1000000*B+10000000*Sr1)
solver.Add(A + 10 * E + 100 * J + 1000 * B + 10000 * B + 100000 * E + 1000000 * F +
E + 10 * J + 100 * E + 1000 * F + 10000 * G + 100000 * A + 1000000 * F
== F + 10 * E + 100 * E + 1000 * H + 10000 * I + 100000 * F + 1000000 * B + 10000000 * Sr1)
solver.Add(C + 10 * F + 100 * H + 1000 * A + 10000 * I + 100000 * I + 1000000 * J +
F + 10 * I + 100 * B + 1000 * D + 10000 * I + 100000 * D + 1000000 * C + Sr1
== J + 10 * F + 100 * A + 1000 * F + 10000 * H + 100000 * D + 1000000 * D + 10000000 * Sr2)
solver.Add(C+10*F+100*H+1000*A+10000*I+100000*I+1000000*J+
F+10*I+100*B+1000*D+10000*I+100000*D+1000000*C+Sr1
== J+10*F+100*A+1000*F+10000*H+100000*D+1000000*D+10000000*Sr2)
solver.Add(A + 10 * J + 100 * J + 1000 * I + 10000 * A + 100000 * B +
B + 10 * A + 100 * G + 1000 * F + 10000 * H + 100000 * D + Sr2
== C + 10 * A + 100 * G + 1000 * E + 10000 * J + 100000 * G)
#
# search and result
#
db = solver.Phase(LD,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.Add(A+10*J+100*J+1000*I+10000*A+100000*B+
B+10*A+100*G+1000*F+10000*H+100000*D+Sr2
== C+10*A+100*G+1000*E+10000*J+100000*G)
#
# search and result
#
db = solver.Phase(LD,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.NewSearch(db)
num_solutions = 0
str = "ABCDEFGHIJ"
while solver.NextSolution():
num_solutions += 1
for (letter, val) in [(str[i], LD[i].Value()) for i in range(len(LD))]:
print "%s: %i" % (letter, val)
print
solver.EndSearch()
solver.NewSearch(db)
num_solutions = 0
str = "ABCDEFGHIJ"
while solver.NextSolution():
num_solutions += 1
for (letter, val) in [(str[i], LD[i].Value()) for i in range(len(LD))]:
print "%s: %i" % (letter, val)
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -40,7 +40,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -48,95 +49,91 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Crypto problem')
# Create the solver.
solver = pywrapcp.Solver("Crypto problem")
#
# data
#
num_letters = 26
#
# data
#
num_letters = 26
BALLET = 45
CELLO = 43
CONCERT = 74
FLUTE = 30
FUGUE = 50
GLEE = 66
JAZZ = 58
LYRE = 47
OBOE = 53
OPERA = 65
POLKA = 59
QUARTET = 50
SAXOPHONE = 134
SCALE = 51
SOLO = 37
SONG = 61
SOPRANO = 82
THEME = 72
VIOLIN = 100
WALTZ = 34
BALLET = 45
CELLO = 43
CONCERT = 74
FLUTE = 30
FUGUE = 50
GLEE = 66
JAZZ = 58
LYRE = 47
OBOE = 53
OPERA = 65
POLKA = 59
QUARTET = 50
SAXOPHONE = 134
SCALE = 51
SOLO = 37
SONG = 61
SOPRANO = 82
THEME = 72
VIOLIN = 100
WALTZ = 34
#
# variables
#
LD = [solver.IntVar(1, num_letters, "LD[%i]" % i) for i in range(num_letters)]
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z = LD
#
# variables
#
LD = [solver.IntVar(1, num_letters, 'LD[%i]' % i) for i in range(num_letters)]
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z = LD
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
solver.Add(B + A + L + L + E + T == BALLET)
solver.Add(C + E + L + L + O == CELLO)
solver.Add(C + O + N + C + E + R + T == CONCERT)
solver.Add(F + L + U + T + E == FLUTE)
solver.Add(F + U + G + U + E == FUGUE)
solver.Add(G + L + E + E == GLEE)
solver.Add(J + A + Z + Z == JAZZ)
solver.Add(L + Y + R + E == LYRE)
solver.Add(O + B + O + E == OBOE)
solver.Add(O + P + E + R + A == OPERA)
solver.Add(P + O + L + K + A == POLKA)
solver.Add(Q + U + A + R + T + E + T == QUARTET)
solver.Add(S + A + X + O + P + H + O + N + E == SAXOPHONE)
solver.Add(S + C + A + L + E == SCALE)
solver.Add(S + O + L + O == SOLO)
solver.Add(S + O + N + G == SONG)
solver.Add(S + O + P + R + A + N + O == SOPRANO)
solver.Add(T + H + E + M + E == THEME)
solver.Add(V + I + O + L + I + N == VIOLIN)
solver.Add(W + A + L + T + Z == WALTZ)
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
solver.Add( B + A + L + L + E + T == BALLET)
solver.Add( C + E + L + L + O == CELLO)
solver.Add( C + O + N + C + E + R + T == CONCERT)
solver.Add( F + L + U + T + E == FLUTE)
solver.Add( F + U + G + U + E == FUGUE)
solver.Add( G + L + E + E == GLEE)
solver.Add( J + A + Z + Z == JAZZ)
solver.Add( L + Y + R + E == LYRE)
solver.Add( O + B + O + E == OBOE)
solver.Add( O + P + E + R + A == OPERA)
solver.Add( P + O + L + K + A == POLKA)
solver.Add( Q + U + A + R + T + E + T == QUARTET)
solver.Add(S + A + X + O + P + H + O + N + E == SAXOPHONE)
solver.Add( S + C + A + L + E == SCALE)
solver.Add( S + O + L + O == SOLO)
solver.Add( S + O + N + G == SONG)
solver.Add( S + O + P + R + A + N + O == SOPRANO)
solver.Add( T + H + E + M + E == THEME)
solver.Add( V + I + O + L + I + N == VIOLIN)
solver.Add( W + A + L + T + Z == WALTZ)
#
# search and result
#
db = solver.Phase(LD,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
#
# search and result
#
db = solver.Phase(LD,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
num_solutions = 0
str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while solver.NextSolution():
num_solutions += 1
for (letter, val) in [(str[i], LD[i].Value()) for i in range(num_letters)]:
print "%s: %i" % (letter, val)
print
solver.EndSearch()
num_solutions = 0
str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while solver.NextSolution():
num_solutions += 1
for (letter, val) in [(str[i], LD[i].Value()) for i in range(num_letters)]:
print "%s: %i" % (letter, val)
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -56,75 +56,74 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def decreasing(solver, x):
for i in range(len(x)-1):
solver.Add(x[i] <= x[i+1])
for i in range(len(x) - 1):
solver.Add(x[i] <= x[i + 1])
def main():
# Create the solver.
solver = pywrapcp.Solver('Curious set of integers')
# Create the solver.
solver = pywrapcp.Solver("Curious set of integers")
#
# data
#
n = 5
max_val = 10000
#
# data
#
n = 5
max_val = 10000
#
# variables
#
x = [solver.IntVar(0, max_val, 'x[%i]' % i) for i in range(n)]
#
# variables
#
x = [solver.IntVar(0, max_val, "x[%i]" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
decreasing(solver, x)
#
# constraints
#
solver.Add(solver.AllDifferent(x))
decreasing(solver, x)
for i in range(n):
for j in range(n):
if i !=j:
p = solver.IntVar(0, max_val, "p[%i,%i]" % (i,j))
solver.Add(p*p-1 == (x[i]*x[j]))
for i in range(n):
for j in range(n):
if i != j:
p = solver.IntVar(0, max_val, "p[%i,%i]" % (i, j))
solver.Add(p * p - 1 == (x[i] * x[j]))
# This is the original problem:
# Which is the fifth number?
v = [1, 3, 8, 120]
b = [solver.IsMemberVar(x[i], v) for i in range(n)]
solver.Add(solver.Sum(b) == 4)
#
# search and result
#
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "x:", [x[i].Value() for i in range(n)]
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
# This is the original problem:
# Which is the fifth number?
v = [1,3,8,120]
b = [solver.IsMemberVar(x[i], v) for i in range(n)]
solver.Add(solver.Sum(b) == 4)
#
# search and result
#
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "x:", [x[i].Value() for i in range(n)]
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -16,8 +16,10 @@
de Bruijn sequences in Google CP Solver.
Implementation of de Bruijn sequences in Minizinc, both 'classical' and 'arbitrary'.
The 'arbitrary' version is when the length of the sequence (m here) is < base**n.
Implementation of de Bruijn sequences in Minizinc, both 'classical' and
'arbitrary'.
The 'arbitrary' version is when the length of the sequence (m here) is <
base**n.
Compare with the the web based programs:
@@ -37,158 +39,159 @@
* JaCoP: http://hakank.org/JaCoP/DeBruijn.java
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
# converts a number (s) <-> an array of numbers (t) in the specific base.
def toNum(solver, t, s, base):
tlen = len(t)
solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)]))
tlen = len(t)
solver.Add(
s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)]))
def main(base=2, n=3, m=8):
# Create the solver.
solver = pywrapcp.Solver('de Bruijn sequences')
# Create the solver.
solver = pywrapcp.Solver("de Bruijn sequences")
#
# data
#
#base = 2 # the base to use, i.e. the alphabet 0..n-1
#n = 3 # number of bits to use (n = 4 -> 0..base^n-1 = 0..2^4 -1, i.e. 0..15)
#m = base**n # the length of the sequence. For "arbitrary" de Bruijn sequences
#
# data
#
# base = 2 # the base to use, i.e. the alphabet 0..n-1
# n = 3 # number of bits to use (n = 4 -> 0..base^n-1 = 0..2^4 -1, i.e. 0..15)
# m = base**n # the length of the sequence. For "arbitrary" de Bruijn
# sequences
# base = 4
# n = 4
# m = base**n
# base = 4
# n = 4
# m = base**n
## harder problem
#base = 13
#n = 4
#m = 52
# harder problem
#base = 13
#n = 4
#m = 52
# for n = 4 with different value of base
# base = 2 0.030 seconds 16 failures
# base = 3 0.041 108
# base = 4 0.070 384
# base = 5 0.231 1000
# base = 6 0.736 2160
# base = 7 2.2 seconds 4116
# base = 8 6 seconds 7168
# base = 9 16 seconds 11664
# base = 10 42 seconds 18000
# base = 6
# n = 4
# m = base**n
# for n = 4 with different value of base
# base = 2 0.030 seconds 16 failures
# base = 3 0.041 108
# base = 4 0.070 384
# base = 5 0.231 1000
# base = 6 0.736 2160
# base = 7 2.2 seconds 4116
# base = 8 6 seconds 7168
# base = 9 16 seconds 11664
# base = 10 42 seconds 18000
# base = 6
# n = 4
# m = base**n
# if True then ensure that the number of occurrences of 0..base-1 is
# the same (and if m mod base = 0)
check_same_gcc = True
# if True then ensure that the number of occurrences of 0..base-1 is
# the same (and if m mod base = 0)
check_same_gcc = True
print "base: %i n: %i m: %i" % (base, n, m)
if check_same_gcc:
print "Checks gcc"
print "base: %i n: %i m: %i" % (base, n, m)
if check_same_gcc:
print "Checks gcc"
# declare variables
x = [solver.IntVar(0, (base ** n) - 1, "x%i" % i) for i in range(m)]
binary = {}
for i in range(m):
for j in range(n):
binary[(i, j)] = solver.IntVar(0, base - 1, "x_%i_%i" % (i, j))
bin_code = [solver.IntVar(0, base - 1, "bin_code%i" % i) for i in range(m)]
# declare variables
x = [solver.IntVar(0,(base**n)-1, 'x%i' % i) for i in range(m)]
binary = {}
for i in range(m):
for j in range(n):
binary[(i,j)] = solver.IntVar(0,base-1, 'x_%i_%i' % (i, j))
#
# constraints
#
#solver.Add(solver.AllDifferent([x[i] for i in range(m)]))
solver.Add(solver.AllDifferent(x))
bin_code = [solver.IntVar(0,base-1, 'bin_code%i' % i) for i in range(m)]
# converts x <-> binary
for i in range(m):
t = [solver.IntVar(0, base - 1, "t_%i" % j) for j in range(n)]
toNum(solver, t, x[i], base)
for j in range(n):
solver.Add(binary[(i, j)] == t[j])
#
# constraints
#
#solver.Add(solver.AllDifferent([x[i] for i in range(m)]))
solver.Add(solver.AllDifferent(x))
# the de Bruijn condition
# the first elements in binary[i] is the same as the last
# elements in binary[i-i]
for i in range(1, m - 1):
for j in range(1, n - 1):
solver.Add(binary[(i - 1, j)] == binary[(i, j - 1)])
# converts x <-> binary
for i in range(m):
t = [ solver.IntVar(0,base-1, 't_%i' % j) for j in range(n) ]
toNum(solver, t, x[i], base)
for j in range(n):
solver.Add(binary[(i,j)] == t[j])
# ... and around the corner
for j in range(1, n):
solver.Add(binary[(m - 1, j)] == binary[(0, j - 1)])
# converts binary -> bin_code
for i in range(m):
solver.Add(bin_code[i] == binary[(i, 0)])
# the de Bruijn condition
# the first elements in binary[i] is the same as the last
# elements in binary[i-i]
for i in range(1,m-1):
for j in range(1,n-1):
solver.Add(binary[(i-1,j)] == binary[(i,j-1)] )
# extra: ensure that all the numbers in the de Bruijn sequence
# (bin_code) has the same occurrences (if check_same_gcc is True
# and mathematically possible)
gcc = [solver.IntVar(0, m, "gcc%i" % i) for i in range(base)]
solver.Add(solver.Distribute(bin_code, range(base), gcc))
if check_same_gcc and m % base == 0:
for i in range(1, base):
solver.Add(gcc[i] == gcc[i - 1])
# ... and around the corner
for j in range(1,n):
solver.Add(binary[(m-1,j)] == binary[(0,j-1)])
#
# solution and search
#
solution = solver.Assignment()
solution.Add([x[i] for i in range(m)])
solution.Add([bin_code[i] for i in range(m)])
# solution.Add([binary[(i,j)] for i in range(m) for j in range(n)])
solution.Add([gcc[i] for i in range(base)])
# converts binary -> bin_code
for i in range(m):
solver.Add(bin_code[i] == binary[(i,0)])
db = solver.Phase([x[i] for i in range(m)] + [bin_code[i] for i in range(m)],
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_MIN_VALUE)
# extra: ensure that all the numbers in the de Bruijn sequence
# (bin_code) has the same occurrences (if check_same_gcc is True
# and mathematically possible)
gcc = [solver.IntVar(0,m,'gcc%i' %i) for i in range(base) ]
solver.Add(solver.Distribute(bin_code, range(base), gcc))
if check_same_gcc and m % base == 0:
for i in range(1,base):
solver.Add(gcc[i] == gcc[i-1])
num_solutions = 0
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nSolution %i" % num_solutions
print "x:", [x[i].Value() for i in range(m)]
print "gcc:", [gcc[i].Value() for i in range(base)]
print "de Bruijn sequence:", [bin_code[i].Value() for i in range(m)]
# for i in range(m):
# for j in range(n):
# print binary[(i,j)].Value(),
# print
# print
solver.EndSearch()
#
# solution and search
#
solution = solver.Assignment()
solution.Add([x[i] for i in range(m)])
solution.Add([bin_code[i] for i in range(m)])
# solution.Add([binary[(i,j)] for i in range(m) for j in range(n)])
solution.Add([gcc[i] for i in range(base)])
db = solver.Phase([x[i] for i in range(m)] + [bin_code[i] for i in range(m)] ,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_MIN_VALUE)
num_solutions = 0
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nSolution %i" % num_solutions
print "x:", [x[i].Value() for i in range(m)]
print "gcc:", [gcc[i].Value() for i in range(base)]
print "de Bruijn sequence:", [bin_code[i].Value() for i in range(m)]
#for i in range(m):
# for j in range(n):
# print binary[(i,j)].Value(),
# print
#print
solver.EndSearch()
if num_solutions == 0:
print "No solution found"
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if num_solutions == 0:
print "No solution found"
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
base = 2
n = 3
m = base**n
if __name__ == '__main__':
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
if len(sys.argv) > 3:
m = string.atoi(sys.argv[3])
n = 3
m = base ** n
if __name__ == "__main__":
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
if len(sys.argv) > 3:
m = string.atoi(sys.argv[3])
main(base, n, m)
main(base, n, m)

View File

@@ -41,46 +41,43 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main(unused_argv):
# Create the solver.
solver = pywrapcp.Solver('Diet')
solver = pywrapcp.Solver("Diet")
#
# data
#
n = 4
price = [ 50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
price = [50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
# nutritions for each product
calories = [400, 200, 150, 500]
chocolate = [3,2,0,0]
sugar = [2,2,4,4]
fat = [2,4,1,5]
calories = [400, 200, 150, 500]
chocolate = [3, 2, 0, 0]
sugar = [2, 2, 4, 4]
fat = [2, 4, 1, 5]
#
# declare variables
#
x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)]
cost = solver.IntVar(0,10000, 'cost')
x = [solver.IntVar(0, 100, "x%d" % i) for i in range(n)]
cost = solver.IntVar(0, 10000, "cost")
#
# constraints
#
solver.Add(solver.Sum([x[i]*calories[i] for i in range(n)]) >= limits[0])
solver.Add(solver.Sum([x[i]*chocolate[i] for i in range(n)]) >= limits[1])
solver.Add(solver.Sum([x[i]*sugar[i] for i in range(n)]) >= limits[2])
solver.Add(solver.Sum([x[i]*fat[i] for i in range(n)]) >= limits[3])
solver.Add(solver.Sum([x[i] * calories[i] for i in range(n)]) >= limits[0])
solver.Add(solver.Sum([x[i] * chocolate[i] for i in range(n)]) >= limits[1])
solver.Add(solver.Sum([x[i] * sugar[i] for i in range(n)]) >= limits[2])
solver.Add(solver.Sum([x[i] * fat[i] for i in range(n)]) >= limits[3])
# objective
objective = solver.Minimize(cost, 1)
@@ -98,12 +95,12 @@ def main(unused_argv):
solver.Solve(solver.Phase(x + [cost],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[objective, search_log, collector])
[objective, search_log, collector])
# get the first (and only) solution
print "cost:", collector.ObjectiveValue(0)
print [("abcdefghij"[i],collector.Value(0, x[i])) for i in range(n)]
print [("abcdefghij"[i], collector.Value(0, x[i])) for i in range(n)]
print
print "failures:", solver.Failures()
print "branches:", solver.Branches()
@@ -111,5 +108,5 @@ def main(unused_argv):
print
if __name__ == '__main__':
if __name__ == "__main__":
main("cp sample")

View File

@@ -43,45 +43,43 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main(unused_argv):
# Create the solver.
solver = pywrapcp.Solver('Diet')
solver = pywrapcp.Solver("Diet")
#
# data
#
n = 4
price = [ 50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
price = [50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
# nutritions for each product
calories = [400, 200, 150, 500]
chocolate = [3,2,0,0]
sugar = [2,2,4,4]
fat = [2,4,1,5]
calories = [400, 200, 150, 500]
chocolate = [3, 2, 0, 0]
sugar = [2, 2, 4, 4]
fat = [2, 4, 1, 5]
#
# declare variables
#
x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)]
cost = solver.IntVar(0,10000, 'cost')
x = [solver.IntVar(0, 100, "x%d" % i) for i in range(n)]
cost = solver.IntVar(0, 10000, "cost")
#
# constraints
#
solver.Add(solver.ScalProd(x,calories) >= limits[0])
solver.Add(solver.ScalProd(x,chocolate) >= limits[1])
solver.Add(solver.ScalProd(x,sugar) >= limits[2])
solver.Add(solver.ScalProd(x,fat) >= limits[3])
solver.Add(solver.ScalProd(x, calories) >= limits[0])
solver.Add(solver.ScalProd(x, chocolate) >= limits[1])
solver.Add(solver.ScalProd(x, sugar) >= limits[2])
solver.Add(solver.ScalProd(x, fat) >= limits[3])
# objective
objective = solver.Minimize(cost, 1)
@@ -99,7 +97,7 @@ def main(unused_argv):
solver.Solve(solver.Phase(x + [cost],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[objective, search_log, collector])
[objective, search_log, collector])
# get the first (and only) solution
print "cost:", collector.ObjectiveValue(0)
@@ -111,5 +109,5 @@ def main(unused_argv):
print
if __name__ == '__main__':
if __name__ == "__main__":
main("cp sample")

View File

@@ -32,14 +32,15 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -51,39 +52,38 @@ def main(sol = 'GLPK'):
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CBC
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
#
n = 4
price = [ 50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
price = [50, 20, 30, 80] # in cents
limits = [500, 6, 10, 8] # requirements for each nutrition type
# nutritions for each product
calories = [400, 200, 150, 500]
chocolate = [3,2,0,0]
sugar = [2,2,4,4]
fat = [2,4,1,5]
calories = [400, 200, 150, 500]
chocolate = [3, 2, 0, 0]
sugar = [2, 2, 4, 4]
fat = [2, 4, 1, 5]
#
# declare variables
#
x = [solver.IntVar(0, 100, 'x%d' % i) for i in range(n)]
cost = solver.Sum([x[i]*price[i] for i in range(n)])
cost = solver.Sum([x[i] * price[i] for i in range(n)])
#
# constraints
#
solver.Add(solver.Sum([x[i]*calories[i]
solver.Add(solver.Sum([x[i] * calories[i]
for i in range(n)]) >= limits[0])
solver.Add(solver.Sum([x[i]*chocolate[i]
solver.Add(solver.Sum([x[i] * chocolate[i]
for i in range(n)]) >= limits[1])
solver.Add(solver.Sum([x[i]*sugar[i]
solver.Add(solver.Sum([x[i] * sugar[i]
for i in range(n)]) >= limits[2])
solver.Add(solver.Sum([x[i]*fat[i]
solver.Add(solver.Sum([x[i] * fat[i]
for i in range(n)]) >= limits[3])
# objective
@@ -94,16 +94,15 @@ def main(sol = 'GLPK'):
#
solver.Solve()
print "Cost:", solver.Objective().Value()
print 'Cost:', solver.Objective().Value()
print [int(x[i].SolutionValue()) for i in range(n)]
print
print "WallTime:", solver.WallTime()
print 'WallTime:', solver.WallTime()
if sol == 'CBC':
print 'iterations:', solver.Iterations()
if __name__ == '__main__':
sol = 'GLPK'

View File

@@ -51,7 +51,8 @@
* SICStus: http://hakank.org/sicstus/discrete_tomography.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
@@ -59,101 +60,100 @@ from ortools.constraint_solver import pywrapcp
def main(row_sums="", col_sums=""):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
if row_sums == "":
print "Using default problem instance"
row_sums = [0,0,8,2,6,4,5,3,7,0,0]
col_sums = [0,0,7,1,6,3,4,5,2,7,0,0]
#
# data
#
if row_sums == "":
print "Using default problem instance"
row_sums = [0, 0, 8, 2, 6, 4, 5, 3, 7, 0, 0]
col_sums = [0, 0, 7, 1, 6, 3, 4, 5, 2, 7, 0, 0]
r = len(row_sums)
c = len(col_sums)
r = len(row_sums)
c = len(col_sums)
# declare variables
x = []
for i in range(r):
t = []
for j in range(c):
t.append(solver.IntVar(0, 1, "x[%i,%i]" % (i, j)))
x.append(t)
x_flat = [x[i][j] for i in range(r) for j in range(c)]
#
# constraints
#
[solver.Add(solver.Sum([x[i][j] for j in range(c)]) == row_sums[i])
for i in range(r)]
[solver.Add(solver.Sum([x[i][j] for i in range(r)]) == col_sums[j])
for j in range(c)]
# declare variables
x = []
for i in range(r):
t = []
for j in range(c):
t.append(solver.IntVar(0,1, 'x[%i,%i]'%(i,j)))
x.append(t)
x_flat = [x[i][j] for i in range(r) for j in range(c)]
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
#
# constraints
#
[solver.Add(solver.Sum([x[i][j] for j in range(c)]) == row_sums[i]) for i in range(r)]
[solver.Add(solver.Sum([x[i][j] for i in range(r)]) == col_sums[j]) for j in range(c)]
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print_solution(x, r, c, row_sums, col_sums)
print
num_solutions += 1
solver.EndSearch()
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print_solution(x, r, c, row_sums, col_sums)
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
#
# Print solution
#
def print_solution(x, rows, cols, row_sums, col_sums):
print " ",
print " ",
for j in range(cols):
print col_sums[j],
print
for i in range(rows):
print row_sums[i],
for j in range(cols):
print col_sums[j],
print
for i in range(rows):
print row_sums[i],
for j in range(cols):
if x[i][j].Value() == 1:
print "#",
else:
print ".",
print ''
if x[i][j].Value() == 1:
print "#",
else:
print ".",
print ""
#
# Read a problem instance from a file
#
def read_problem(file):
f = open(file, 'r')
row_sums = f.readline()
col_sums = f.readline()
row_sums = [int(r) for r in (row_sums.rstrip()).split(",")]
col_sums = [int(c) for c in (col_sums.rstrip()).split(",")]
f = open(file, "r")
row_sums = f.readline()
col_sums = f.readline()
row_sums = [int(r) for r in (row_sums.rstrip()).split(",")]
col_sums = [int(c) for c in (col_sums.rstrip()).split(",")]
return [row_sums, col_sums]
if __name__ == '__main__':
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[row_sums, col_sums] = read_problem(file)
main(row_sums, col_sums)
else:
main()
return [row_sums, col_sums]
if __name__ == "__main__":
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[row_sums, col_sums] = read_problem(file)
main(row_sums, col_sums)
else:
main()

View File

@@ -48,10 +48,12 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import string, sys
import string
import sys
from ortools.constraint_solver import pywrapcp
@@ -65,114 +67,115 @@ from ortools.constraint_solver import pywrapcp
# The ECLiPSe source code:
# http://www.hakank.org/eclipse/modulo_propagator.ecl
#
def my_mod(solver, x, y, r):
if not isinstance(y, int):
solver.Add(y != 0)
if not isinstance(y, int):
solver.Add(y != 0)
lbx = x.Min()
ubx = x.Max()
ubx_neg = -ubx
lbx_neg = -lbx
min_x = min(lbx, ubx_neg)
max_x = max(ubx, lbx_neg)
lbx = x.Min()
ubx = x.Max()
ubx_neg = -ubx
lbx_neg = -lbx
min_x = min(lbx, ubx_neg)
max_x = max(ubx, lbx_neg)
d = solver.IntVar(max(0,min_x), max_x, 'd')
d = solver.IntVar(max(0, min_x), max_x, "d")
if not isinstance(r, int):
solver.Add(r >= 0)
solver.Add(x*r >= 0)
if not isinstance(r, int):
solver.Add(r >= 0)
solver.Add(x * r >= 0)
if not isinstance(r, int) and not isinstance(r, int):
solver.Add(-abs(y) < r)
solver.Add(r < abs(y))
if not isinstance(r, int) and not isinstance(r, int):
solver.Add(-abs(y) < r)
solver.Add(r < abs(y))
solver.Add(min_x <= d)
solver.Add(d <= max_x)
solver.Add(x == y*d+r)
solver.Add(min_x <= d)
solver.Add(d <= max_x)
solver.Add(x == y * d + r)
#
# converts a number (s) <-> an array of integers (t) in the specific base.
#
def toNum(solver, t, s, base):
tlen = len(t)
solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)]))
tlen = len(t)
solver.Add(
s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)]))
def main(base=10):
# Create the solver.
solver = pywrapcp.Solver('Divisible by 9 through 1')
# Create the solver.
solver = pywrapcp.Solver("Divisible by 9 through 1")
# data
m = base**(base-1)-1
n = base - 1
# data
m = base ** (base - 1) - 1
n = base - 1
digits_str = "_0123456789ABCDEFGH"
digits_str = "_0123456789ABCDEFGH"
print "base:", base
print "base:", base
# declare variables
# declare variables
# the digits
x = [solver.IntVar(1, base-1, 'x[%i]' % i) for i in range(n)]
# the digits
x = [solver.IntVar(1, base - 1, "x[%i]" % i) for i in range(n)]
# the numbers, t[0] contains the answer
t = [solver.IntVar(0, m, 't[%i]' % i) for i in range(n)]
# the numbers, t[0] contains the answer
t = [solver.IntVar(0, m, "t[%i]" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
for i in range(n):
mm = base-i-1
toNum(solver, [x[j] for j in range(mm)], t[i], base)
my_mod(solver, t[i], mm, 0)
for i in range(n):
mm = base - i - 1
toNum(solver, [x[j] for j in range(mm)], t[i], base)
my_mod(solver, t[i], mm, 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(t)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(t)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "x: ", [x[i].Value() for i in range(n)]
print "t: ", [t[i].Value() for i in range(n)]
print "number base 10: %i base %i: %s" % (t[0].Value(),
base,
"".join([digits_str[x[i].Value() + 1] for i in range(n)]))
print
num_solutions += 1
solver.EndSearch()
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "x: ", [x[i].Value() for i in range(n)]
print "t: ", [t[i].Value() for i in range(n)]
print "number base 10: %i base %i: %s" % (t[0].Value(),\
base,
"".join([digits_str[x[i].Value()+1] for i in range(n)]))
print
num_solutions += 1
solver.EndSearch()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
base = 10
default_base = 10
max_base = 16
if __name__ == '__main__':
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if base > max_base:
print "Sorry, max allowed base is %i. Setting base to %i..." % (max_base, default_base)
base = default_base
main(base)
if __name__ == "__main__":
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if base > max_base:
print "Sorry, max allowed base is %i. Setting base to %i..." % (max_base, default_base)
base = default_base
main(base)
# for base in range(2, 17):
# print
# main(base)
# for base in range(2, 17):
# print
# main(base)

View File

@@ -13,6 +13,7 @@
from ortools.constraint_solver import pywrapcp
def dudeney(n):
solver = pywrapcp.Solver('Dudeney')
x = [solver.IntVar(range(10), 'x' + str(i)) for i in range(n)]

View File

@@ -60,7 +60,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -68,140 +69,138 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Einav puzzle')
# Create the solver.
solver = pywrapcp.Solver('Einav puzzle')
#
# data
#
#
# data
#
# small problem
# rows = 3;
# cols = 3;
# data = [
# [ 33, 30, -10],
# [-16, 19, 9],
# [-17, -12, -14]
# ]
# small problem
# rows = 3;
# cols = 3;
# data = [
# [ 33, 30, -10],
# [-16, 19, 9],
# [-17, -12, -14]
# ]
# Full problem
rows = 27
cols = 9
data = [
[33,30,10,-6,18,-7,-11,23,-6],
[16,-19,9,-26,-8,-19,-8,-21,-14],
[17,12,-14,31,-30,13,-13,19,16],
[-6,-11,1,17,-12,-4,-7,14,-21],
[18,-31,34,-22,17,-19,20,24,6],
[33,-18,17,-15,31,-5,3,27,-3],
[-18,-20,-18,31,6,4,-2,-12,24],
[27,14,4,-29,-3,5,-29,8,-12],
[-15,-7,-23,23,-9,-8,6,8,-12],
[33,-23,-19,-4,-8,-7,11,-12,31],
[-20,19,-15,-30,11,32,7,14,-5],
[-23,18,-32,-2,-31,-7,8,24,16],
[32,-4,-10,-14,-6,-1,0,23,23],
[25,0,-23,22,12,28,-27,15,4],
[-30,-13,-16,-3,-3,-32,-3,27,-31],
[22,1,26,4,-2,-13,26,17,14],
[-9,-18,3,-20,-27,-32,-11,27,13],
[-17,33,-7,19,-32,13,-31,-2,-24],
[-31,27,-31,-29,15,2,29,-15,33],
[-18,-23,15,28,0,30,-4,12,-32],
[-3,34,27,-25,-18,26,1,34,26],
[-21,-31,-10,-13,-30,-17,-12,-26,31],
[23,-31,-19,21,-17,-10,2,-23,23],
[-3,6,0,-3,-32,0,-10,-25,14],
[-19,9,14,-27,20,15,-5,-27,18],
[11,-6,24,7,-17,26,20,-31,-25],
[-25,4,-16,30,33,23,-4,-4,23]
]
# Full problem
rows = 27
cols = 9
data = [
[33, 30, 10, -6, 18, -7, -11, 23, -6],
[16, -19, 9, -26, -8, -19, -8, -21, -14],
[17, 12, -14, 31, -30, 13, -13, 19, 16],
[-6, -11, 1, 17, -12, -4, -7, 14, -21],
[18, -31, 34, -22, 17, -19, 20, 24, 6],
[33, -18, 17, -15, 31, -5, 3, 27, -3],
[-18, -20, -18, 31, 6, 4, -2, -12, 24],
[27, 14, 4, -29, -3, 5, -29, 8, -12],
[-15, -7, -23, 23, -9, -8, 6, 8, -12],
[33, -23, -19, -4, -8, -7, 11, -12, 31],
[-20, 19, -15, -30, 11, 32, 7, 14, -5],
[-23, 18, -32, -2, -31, -7, 8, 24, 16],
[32, -4, -10, -14, -6, -1, 0, 23, 23],
[25, 0, -23, 22, 12, 28, -27, 15, 4],
[-30, -13, -16, -3, -3, -32, -3, 27, -31],
[22, 1, 26, 4, -2, -13, 26, 17, 14],
[-9, -18, 3, -20, -27, -32, -11, 27, 13],
[-17, 33, -7, 19, -32, 13, -31, -2, -24],
[-31, 27, -31, -29, 15, 2, 29, -15, 33],
[-18, -23, 15, 28, 0, 30, -4, 12, -32],
[-3, 34, 27, -25, -18, 26, 1, 34, 26],
[-21, -31, -10, -13, -30, -17, -12, -26, 31],
[23, -31, -19, 21, -17, -10, 2, -23, 23],
[-3, 6, 0, -3, -32, 0, -10, -25, 14],
[-19, 9, 14, -27, 20, 15, -5, -27, 18],
[11, -6, 24, 7, -17, 26, 20, -31, -25],
[-25, 4, -16, 30, 33, 23, -4, -4, 23]
]
#
# variables
#
x = {}
for i in range(rows):
for j in range(cols):
x[i,j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i,j))
x_flat = [x[i,j] for i in range(rows) for j in range(cols)]
row_sums = [solver.IntVar(0, 300, 'row_sums(%i)' % i)
for i in range(rows)]
col_sums = [solver.IntVar(0, 300, 'col_sums(%i)' % j)
for j in range(cols)]
row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i)
for i in range(rows)]
col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j)
for j in range(cols)]
# total sum: to be minimized
total_sum = solver.IntVar(0, 1000, 'total_sum')
#
# constraints
#
for i in range(rows):
for j in range(cols):
solver.Add(x[i,j] == data[i][j]*row_signs[i]*col_signs[j])
total_sum_a = [data[i][j]*row_signs[i]*col_signs[j]
for i in range(rows) for j in range(cols) ]
solver.Add(total_sum == solver.Sum(total_sum_a))
# row sums
for i in range(rows):
s = [row_signs[i]*col_signs[j]*data[i][j]
for j in range(cols)]
solver.Add(row_sums[i] == solver.Sum(s))
# column sums
#
# variables
#
x = {}
for i in range(rows):
for j in range(cols):
s = [row_signs[i]*col_signs[j]*data[i][j]
for i in range(rows)]
solver.Add(col_sums[j] == solver.Sum(s))
x[i, j] = solver.IntVar(-100, 100, 'x[%i,%i]' % (i, j))
x_flat = [x[i, j] for i in range(rows) for j in range(cols)]
# objective
objective = solver.Minimize(total_sum, 1)
row_sums = [solver.IntVar(0, 300, 'row_sums(%i)' % i)
for i in range(rows)]
col_sums = [solver.IntVar(0, 300, 'col_sums(%i)' % j)
for j in range(cols)]
#
# search and result
#
# Note: The order of the variables makes a big difference.
# If row_signs are before col_sign it is much slower.
db = solver.Phase(col_signs + row_signs,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MAX_VALUE)
row_signs = [solver.IntVar([-1, 1], 'row_signs(%i)' % i)
for i in range(rows)]
col_signs = [solver.IntVar([-1, 1], 'col_signs(%i)' % j)
for j in range(cols)]
solver.NewSearch(db, [objective])
# total sum: to be minimized
total_sum = solver.IntVar(0, 1000, 'total_sum')
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total_sum:', total_sum.Value()
print 'row_sums:', [row_sums[i].Value() for i in range(rows)]
print 'col_sums:', [col_sums[j].Value() for j in range(cols)]
print 'row_signs:', [row_signs[i].Value() for i in range(rows)]
print 'col_signs:', [col_signs[j].Value() for j in range(cols)]
print 'x:'
for i in range(rows):
for j in range(cols):
print '%3i' % x[i,j].Value(),
print
print
#
# constraints
#
for i in range(rows):
for j in range(cols):
solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j])
solver.EndSearch()
total_sum_a = [data[i][j] * row_signs[i] * col_signs[j]
for i in range(rows) for j in range(cols)]
solver.Add(total_sum == solver.Sum(total_sum_a))
# row sums
for i in range(rows):
s = [row_signs[i] * col_signs[j] * data[i][j]
for j in range(cols)]
solver.Add(row_sums[i] == solver.Sum(s))
# column sums
for j in range(cols):
s = [row_signs[i] * col_signs[j] * data[i][j]
for i in range(rows)]
solver.Add(col_sums[j] == solver.Sum(s))
# objective
objective = solver.Minimize(total_sum, 1)
#
# search and result
#
# Note: The order of the variables makes a big difference.
# If row_signs are before col_sign it is much slower.
db = solver.Phase(col_signs + row_signs,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total_sum:', total_sum.Value()
print 'row_sums:', [row_sums[i].Value() for i in range(rows)]
print 'col_sums:', [col_sums[j].Value() for j in range(cols)]
print 'row_signs:', [row_signs[i].Value() for i in range(rows)]
print 'col_signs:', [col_signs[j].Value() for j in range(cols)]
print 'x:'
for i in range(rows):
for j in range(cols):
print '%3i' % x[i, j].Value(),
print
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -61,7 +61,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -69,131 +70,128 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Einav puzzle')
# Create the solver.
solver = pywrapcp.Solver("Einav puzzle")
#
# data
#
#
# data
#
# small problem
# rows = 3;
# cols = 3;
# data = [
# [ 33, 30, -10],
# [-16, 19, 9],
# [-17, -12, -14]
# ]
# small problem
# rows = 3;
# cols = 3;
# data = [
# [ 33, 30, -10],
# [-16, 19, 9],
# [-17, -12, -14]
# ]
# Full problem
rows = 27
cols = 9
data = [
[33, 30, 10, -6, 18, -7, -11, 23, -6],
[16, -19, 9, -26, -8, -19, -8, -21, -14],
[17, 12, -14, 31, -30, 13, -13, 19, 16],
[-6, -11, 1, 17, -12, -4, -7, 14, -21],
[18, -31, 34, -22, 17, -19, 20, 24, 6],
[33, -18, 17, -15, 31, -5, 3, 27, -3],
[-18, -20, -18, 31, 6, 4, -2, -12, 24],
[27, 14, 4, -29, -3, 5, -29, 8, -12],
[-15, -7, -23, 23, -9, -8, 6, 8, -12],
[33, -23, -19, -4, -8, -7, 11, -12, 31],
[-20, 19, -15, -30, 11, 32, 7, 14, -5],
[-23, 18, -32, -2, -31, -7, 8, 24, 16],
[32, -4, -10, -14, -6, -1, 0, 23, 23],
[25, 0, -23, 22, 12, 28, -27, 15, 4],
[-30, -13, -16, -3, -3, -32, -3, 27, -31],
[22, 1, 26, 4, -2, -13, 26, 17, 14],
[-9, -18, 3, -20, -27, -32, -11, 27, 13],
[-17, 33, -7, 19, -32, 13, -31, -2, -24],
[-31, 27, -31, -29, 15, 2, 29, -15, 33],
[-18, -23, 15, 28, 0, 30, -4, 12, -32],
[-3, 34, 27, -25, -18, 26, 1, 34, 26],
[-21, -31, -10, -13, -30, -17, -12, -26, 31],
[23, -31, -19, 21, -17, -10, 2, -23, 23],
[-3, 6, 0, -3, -32, 0, -10, -25, 14],
[-19, 9, 14, -27, 20, 15, -5, -27, 18],
[11, -6, 24, 7, -17, 26, 20, -31, -25],
[-25, 4, -16, 30, 33, 23, -4, -4, 23]
]
# Full problem
rows = 27
cols = 9
data = [
[33,30,10,-6,18,-7,-11,23,-6],
[16,-19,9,-26,-8,-19,-8,-21,-14],
[17,12,-14,31,-30,13,-13,19,16],
[-6,-11,1,17,-12,-4,-7,14,-21],
[18,-31,34,-22,17,-19,20,24,6],
[33,-18,17,-15,31,-5,3,27,-3],
[-18,-20,-18,31,6,4,-2,-12,24],
[27,14,4,-29,-3,5,-29,8,-12],
[-15,-7,-23,23,-9,-8,6,8,-12],
[33,-23,-19,-4,-8,-7,11,-12,31],
[-20,19,-15,-30,11,32,7,14,-5],
[-23,18,-32,-2,-31,-7,8,24,16],
[32,-4,-10,-14,-6,-1,0,23,23],
[25,0,-23,22,12,28,-27,15,4],
[-30,-13,-16,-3,-3,-32,-3,27,-31],
[22,1,26,4,-2,-13,26,17,14],
[-9,-18,3,-20,-27,-32,-11,27,13],
[-17,33,-7,19,-32,13,-31,-2,-24],
[-31,27,-31,-29,15,2,29,-15,33],
[-18,-23,15,28,0,30,-4,12,-32],
[-3,34,27,-25,-18,26,1,34,26],
[-21,-31,-10,-13,-30,-17,-12,-26,31],
[23,-31,-19,21,-17,-10,2,-23,23],
[-3,6,0,-3,-32,0,-10,-25,14],
[-19,9,14,-27,20,15,-5,-27,18],
[11,-6,24,7,-17,26,20,-31,-25],
[-25,4,-16,30,33,23,-4,-4,23]
]
#
# variables
#
x = {}
for i in range(rows):
for j in range(cols):
x[i,j] = solver.IntVar(-100, 100, "x[%i,%i]" % (i,j))
x_flat = [x[i,j] for i in range(rows) for j in range(cols)]
row_signs = [solver.IntVar([-1, 1], "row_signs(%i)" % i)
for i in range(rows)]
col_signs = [solver.IntVar([-1, 1], "col_signs(%i)" % j)
for j in range(cols)]
#
# constraints
#
for i in range(rows):
for j in range(cols):
solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j])
total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)])
#
# Note: In einav_puzzle.py row_sums and col_sums are decision variables.
#
# row sums
row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var()
for i in range(rows)]
# >= 0
for i in range(rows):
row_sums[i].SetMin(0)
# column sums
col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var()
for j in range(cols)]
#
# variables
#
x = {}
for i in range(rows):
for j in range(cols):
col_sums[j].SetMin(0)
x[i, j] = solver.IntVar(-100, 100, "x[%i,%i]" % (i, j))
x_flat = [x[i, j] for i in range(rows) for j in range(cols)]
# objective
objective = solver.Minimize(total_sum, 1)
row_signs = [solver.IntVar([-1, 1], "row_signs(%i)" % i)
for i in range(rows)]
col_signs = [solver.IntVar([-1, 1], "col_signs(%i)" % j)
for j in range(cols)]
#
# search and result
#
db = solver.Phase(col_signs + row_signs,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MAX_VALUE)
#
# constraints
#
for i in range(rows):
for j in range(cols):
solver.Add(x[i, j] == data[i][j] * row_signs[i] * col_signs[j])
solver.NewSearch(db, [objective])
total_sum = solver.Sum([x[i, j] for i in range(rows) for j in range(cols)])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Sum =", objective.best()
print "row_sums:", [row_sums[i].Value() for i in range(rows)]
print "col_sums:", [col_sums[j].Value() for j in range(cols)]
for i in range(rows):
for j in range(cols):
print "%3i" % x[i,j].Value(),
print
print
#
# Note: In einav_puzzle.py row_sums and col_sums are decision variables.
#
solver.EndSearch()
# row sums
row_sums = [solver.Sum([x[i, j] for j in range(cols)]).Var()
for i in range(rows)]
# >= 0
for i in range(rows):
row_sums[i].SetMin(0)
# column sums
col_sums = [solver.Sum([x[i, j] for i in range(rows)]).Var()
for j in range(cols)]
for j in range(cols):
col_sums[j].SetMin(0)
# objective
objective = solver.Minimize(total_sum, 1)
#
# search and result
#
db = solver.Phase(col_signs + row_signs,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Sum =", objective.best()
print "row_sums:", [row_sums[i].Value() for i in range(rows)]
print "col_sums:", [col_sums[j].Value() for j in range(cols)]
for i in range(rows):
for j in range(cols):
print "%3i" % x[i, j].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -24,7 +24,8 @@
* SICStus: http://hakank.org/sicstus/eq10.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -32,77 +33,77 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Eq 10')
# Create the solver.
solver = pywrapcp.Solver("Eq 10")
#
# data
#
n = 7
#
# data
#
n = 7
#
# variables
#
X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)]
X1,X2,X3,X4,X5,X6,X7 = X
#
# variables
#
X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)]
X1, X2, X3, X4, X5, X6, X7 = X
#
# constraints
#
solver.Add(0+98527*X1+34588*X2+5872*X3+59422*X5+65159*X7
== 1547604+30704*X4+29649*X6)
#
# constraints
#
solver.Add(0 + 98527 * X1 + 34588 * X2 + 5872 * X3 + 59422 * X5 + 65159 * X7
== 1547604 + 30704 * X4 + 29649 * X6)
solver.Add(0+98957*X2+83634*X3+69966*X4+62038*X5+37164*X6+85413*X7
== 1823553+93989*X1)
solver.Add(
0 + 98957 * X2 + 83634 * X3 + 69966 * X4 + 62038 * X5 + 37164 * X6 + 85413 * X7 == 1823553 + 93989 *
X1)
solver.Add(900032+10949*X1+77761*X2+67052*X5
== 0+80197*X3+61944*X4+92964*X6+44550*X7)
solver.Add(900032 + 10949 * X1 + 77761 * X2 + 67052 * X5
== 0 + 80197 * X3 + 61944 * X4 + 92964 * X6 + 44550 * X7)
solver.Add(0+73947*X1+84391*X3+81310*X5
== 1164380+96253*X2+44247*X4+70582*X6+33054*X7)
solver.Add(0 + 73947 * X1 + 84391 * X3 + 81310 * X5
== 1164380 + 96253 * X2 + 44247 * X4 + 70582 * X6 + 33054 * X7)
solver.Add(0+13057*X3+42253*X4+77527*X5+96552*X7
== 1185471+60152*X1+21103*X2+97932*X6)
solver.Add(0 + 13057 * X3 + 42253 * X4 + 77527 * X5 + 96552 * X7
== 1185471 + 60152 * X1 + 21103 * X2 + 97932 * X6)
solver.Add(1394152+66920*X1+55679*X4
== 0+64234*X2+65337*X3+45581*X5+67707*X6+98038*X7)
solver.Add(1394152 + 66920 * X1 + 55679 * X4 ==
0 + 64234 * X2 + 65337 * X3 + 45581 * X5 + 67707 * X6 + 98038 * X7)
solver.Add(0+68550*X1+27886*X2+31716*X3+73597*X4+38835*X7
== 279091+88963*X5+76391*X6)
solver.Add(0 + 68550 * X1 + 27886 * X2 + 31716 * X3 + 73597 * X4 + 38835 * X7
== 279091 + 88963 * X5 + 76391 * X6)
solver.Add(0+76132*X2+71860*X3+22770*X4+68211*X5+78587*X6
== 480923+48224*X1+82817*X7)
solver.Add(0 + 76132 * X2 + 71860 * X3 + 22770 * X4 + 68211 * X5 + 78587 * X6
== 480923 + 48224 * X1 + 82817 * X7)
solver.Add(519878+94198*X2+87234*X3+37498*X4
== 0+71583*X1+25728*X5+25495*X6+70023*X7)
solver.Add(519878 + 94198 * X2 + 87234 * X3 + 37498 * X4
== 0 + 71583 * X1 + 25728 * X5 + 25495 * X6 + 70023 * X7)
solver.Add(361921+78693*X1+38592*X5+38478*X6
== 0+94129*X2+43188*X3+82528*X4+69025*X7)
solver.Add(361921 + 78693 * X1 + 38592 * X5 + 38478 * X6
== 0 + 94129 * X2 + 43188 * X3 + 82528 * X4 + 69025 * X7)
#
# search and result
#
db = solver.Phase(X,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
#
# search and result
#
db = solver.Phase(X,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "X:", [X[i].Value() for i in range(n)]
print
solver.EndSearch()
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "X:", [X[i].Value() for i in range(n)]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -24,7 +24,8 @@
* SICStus: http://hakank.org/sicstus/eq20.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -32,88 +33,87 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Eq 20')
# Create the solver.
solver = pywrapcp.Solver("Eq 20")
#
# data
#
n = 7
#
# data
#
n = 7
#
# variables
#
X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)]
X0,X1,X2,X3,X4,X5,X6 = X
#
# variables
#
X = [solver.IntVar(0, 10, "X(%i)" % i) for i in range(n)]
X0, X1, X2, X3, X4, X5, X6 = X
#
# constraints
#
solver.Add(-76706*X0 + 98205*X1 + 23445*X2 + 67921*X3 + 24111*X4 +
-48614*X5 + -41906*X6 == 821228)
solver.Add(87059*X0 + -29101*X1 + -5513*X2 + -21219*X3 + 22128*X4 +
7276*X5 + 57308*X6 == 22167)
solver.Add(-60113*X0 + 29475*X1 + 34421*X2 + -76870*X3 + 62646*X4 +
29278*X5 + -15212*X6 == 251591)
solver.Add(49149*X0 + 52871*X1 + -7132*X2 + 56728*X3 + -33576*X4 +
-49530*X5 + -62089*X6 == 146074)
solver.Add(-10343*X0 + 87758*X1 + -11782*X2 + 19346*X3 + 70072*X4 +
-36991*X5 + 44529*X6 == 740061)
solver.Add(85176*X0 + -95332*X1 + -1268*X2 + 57898*X3 + 15883*X4 +
50547*X5 + 83287*X6 == 373854)
solver.Add(-85698*X0 + 29958*X1 + 57308*X2 + 48789*X3 + -78219*X4 +
4657*X5 + 34539*X6 == 249912)
solver.Add(-67456*X0 + 84750*X1 + -51553*X2 + 21239*X3 + 81675*X4 +
-99395*X5 + -4254*X6 == 277271)
solver.Add(94016*X0 + -82071*X1 + 35961*X2 + 66597*X3 + -30705*X4 +
-44404*X5 + -38304*X6 == 25334)
solver.Add(-60301*X0 + 31227*X1 + 93951*X2 + 73889*X3 + 81526*X4 +
-72702*X5 + 68026*X6 == 1410723)
solver.Add(-16835*X0 + 47385*X1 + 97715*X2 + -12640*X3 + 69028*X4 +
76212*X5 + -81102*X6 == 1244857)
solver.Add(-43277*X0 + 43525*X1 + 92298*X2 + 58630*X3 + 92590*X4 +
-9372*X5 + -60227*X6 == 1503588)
solver.Add(-64919*X0 + 80460*X1 + 90840*X2 + -59624*X3 + -75542*X4 +
25145*X5 + -47935*X6 == 18465)
solver.Add(-45086*X0 + 51830*X1 + -4578*X2 + 96120*X3 + 21231*X4 +
97919*X5 + 65651*X6 == 1198280)
solver.Add(85268*X0 + 54180*X1 + -18810*X2 + -48219*X3 + 6013*X4 +
78169*X5 + -79785*X6 == 90614)
solver.Add(8874*X0 + -58412*X1 + 73947*X2 + 17147*X3 + 62335*X4 +
16005*X5 + 8632*X6 == 752447)
solver.Add(71202*X0 + -11119*X1 + 73017*X2 + -38875*X3 + -14413*X4 +
-29234*X5 + 72370*X6 == 129768)
solver.Add(1671*X0 + -34121*X1 + 10763*X2 + 80609*X3 + 42532*X4 +
93520*X5 + -33488*X6 == 915683)
solver.Add(51637*X0 + 67761*X1 + 95951*X2 + 3834*X3 + -96722*X4 +
59190*X5 + 15280*X6 == 533909)
solver.Add(-16105*X0 + 62397*X1 + -6704*X2 + 43340*X3 + 95100*X4 +
-68610*X5 + 58301*X6 == 876370)
#
# constraints
#
solver.Add(-76706 * X0 + 98205 * X1 + 23445 * X2 + 67921 * X3 + 24111 * X4 +
-48614 * X5 + -41906 * X6 == 821228)
solver.Add(87059 * X0 + -29101 * X1 + -5513 * X2 + -21219 * X3 + 22128 * X4 +
7276 * X5 + 57308 * X6 == 22167)
solver.Add(-60113 * X0 + 29475 * X1 + 34421 * X2 + -76870 * X3 + 62646 * X4 +
29278 * X5 + -15212 * X6 == 251591)
solver.Add(49149 * X0 + 52871 * X1 + -7132 * X2 + 56728 * X3 + -33576 * X4 +
-49530 * X5 + -62089 * X6 == 146074)
solver.Add(-10343 * X0 + 87758 * X1 + -11782 * X2 + 19346 * X3 + 70072 * X4 +
-36991 * X5 + 44529 * X6 == 740061)
solver.Add(85176 * X0 + -95332 * X1 + -1268 * X2 + 57898 * X3 + 15883 * X4 +
50547 * X5 + 83287 * X6 == 373854)
solver.Add(-85698 * X0 + 29958 * X1 + 57308 * X2 + 48789 * X3 + -78219 * X4 +
4657 * X5 + 34539 * X6 == 249912)
solver.Add(-67456 * X0 + 84750 * X1 + -51553 * X2 + 21239 * X3 + 81675 * X4 +
-99395 * X5 + -4254 * X6 == 277271)
solver.Add(94016 * X0 + -82071 * X1 + 35961 * X2 + 66597 * X3 + -30705 * X4 +
-44404 * X5 + -38304 * X6 == 25334)
solver.Add(-60301 * X0 + 31227 * X1 + 93951 * X2 + 73889 * X3 + 81526 * X4 +
-72702 * X5 + 68026 * X6 == 1410723)
solver.Add(-16835 * X0 + 47385 * X1 + 97715 * X2 + -12640 * X3 + 69028 * X4 +
76212 * X5 + -81102 * X6 == 1244857)
solver.Add(-43277 * X0 + 43525 * X1 + 92298 * X2 + 58630 * X3 + 92590 * X4 +
-9372 * X5 + -60227 * X6 == 1503588)
solver.Add(-64919 * X0 + 80460 * X1 + 90840 * X2 + -59624 * X3 + -75542 * X4 +
25145 * X5 + -47935 * X6 == 18465)
solver.Add(-45086 * X0 + 51830 * X1 + -4578 * X2 + 96120 * X3 + 21231 * X4 +
97919 * X5 + 65651 * X6 == 1198280)
solver.Add(85268 * X0 + 54180 * X1 + -18810 * X2 + -48219 * X3 + 6013 * X4 +
78169 * X5 + -79785 * X6 == 90614)
solver.Add(8874 * X0 + -58412 * X1 + 73947 * X2 + 17147 * X3 + 62335 * X4 +
16005 * X5 + 8632 * X6 == 752447)
solver.Add(71202 * X0 + -11119 * X1 + 73017 * X2 + -38875 * X3 + -14413 * X4 +
-29234 * X5 + 72370 * X6 == 129768)
solver.Add(1671 * X0 + -34121 * X1 + 10763 * X2 + 80609 * X3 + 42532 * X4 +
93520 * X5 + -33488 * X6 == 915683)
solver.Add(51637 * X0 + 67761 * X1 + 95951 * X2 + 3834 * X3 + -96722 * X4 +
59190 * X5 + 15280 * X6 == 533909)
solver.Add(-16105 * X0 + 62397 * X1 + -6704 * X2 + 43340 * X3 + 95100 * X4 +
-68610 * X5 + 58301 * X6 == 876370)
#
# search and result
#
db = solver.Phase(X,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# search and result
#
db = solver.Phase(X,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "X:", [X[i].Value() for i in range(n)]
print
solver.EndSearch()
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "X:", [X[i].Value() for i in range(n)]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -16,7 +16,8 @@
Fill-a-Pix problem in Google CP Solver.
From http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic
From
http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic
'''
Each puzzle consists of a grid containing clues in various places. The
object is to reveal a hidden picture by painting the squares around each
@@ -47,7 +48,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
@@ -58,129 +60,128 @@ from ortools.constraint_solver import pywrapcp
default_n = 10
X = -1
default_puzzle = [
[X,X,X,X,X,X,X,X,0,X],
[X,8,8,X,2,X,0,X,X,X],
[5,X,8,X,X,X,X,X,X,X],
[X,X,X,X,X,2,X,X,X,2],
[1,X,X,X,4,5,6,X,X,X],
[X,0,X,X,X,7,9,X,X,6],
[X,X,X,6,X,X,9,X,X,6],
[X,X,6,6,8,7,8,7,X,5],
[X,4,X,6,6,6,X,6,X,4],
[X,X,X,X,X,X,3,X,X,X]
]
[X, X, X, X, X, X, X, X, 0, X],
[X, 8, 8, X, 2, X, 0, X, X, X],
[5, X, 8, X, X, X, X, X, X, X],
[X, X, X, X, X, 2, X, X, X, 2],
[1, X, X, X, 4, 5, 6, X, X, X],
[X, 0, X, X, X, 7, 9, X, X, 6],
[X, X, X, 6, X, X, 9, X, X, 6],
[X, X, 6, 6, 8, 7, 8, 7, X, 5],
[X, 4, X, 6, 6, 6, X, 6, X, 4],
[X, X, X, X, X, X, 3, X, X, X]
]
def main(puzzle='', n=''):
# Create the solver.
solver = pywrapcp.Solver('Fill-a-Pix')
# Create the solver.
solver = pywrapcp.Solver('Fill-a-Pix')
#
# data
#
#
# data
#
# Set default problem
if puzzle == '':
puzzle = default_puzzle
n = default_n
else:
print 'n:', n
# Set default problem
if puzzle == '':
puzzle = default_puzzle
n = default_n
else:
print 'n:', n
# for the neighbors of 'this' cell
S = [-1,0,1]
# for the neighbors of 'this' cell
S = [-1, 0, 1]
# print problem instance
print 'Problem:'
# print problem instance
print 'Problem:'
for i in range(n):
for j in range(n):
if puzzle[i][j] == X:
sys.stdout.write('.')
else:
sys.stdout.write(str(puzzle[i][j]))
print
print
#
# declare variables
#
pict = {}
for i in range(n):
for j in range(n):
pict[(i, j)] = solver.IntVar(0, 1, 'pict %i %i' % (i, j))
pict_flat = [pict[i, j] for i in range(n) for j in range(n)]
#
# constraints
#
for i in range(n):
for j in range(n):
if puzzle[i][j] > X:
# this cell is the sum of all the surrounding cells
solver.Add(
puzzle[i][j] == solver.Sum([pict[i + a, j + b]
for a in S for b in S
if i + a >= 0 and
j + b >= 0 and
i + a < n and
j + b < n])
)
#
# solution and search
#
db = solver.Phase(pict_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
print 'Solution:'
while solver.NextSolution():
num_solutions += 1
for i in range(n):
for j in range(n):
if puzzle[i][j] == X:
sys.stdout.write('.')
else:
sys.stdout.write(str(puzzle[i][j]))
print
row = [str(pict[i, j].Value()) for j in range(n)]
for j in range(n):
if row[j] == '0':
row[j] = ' '
else:
row[j] = '#'
print ''.join(row)
print
#
# declare variables
#
pict = {}
for i in range(n):
for j in range(n):
pict[(i,j)] = solver.IntVar(0,1, 'pict %i %i' % (i, j))
pict_flat = [pict[i,j] for i in range(n) for j in range(n)]
#
# constraints
#
for i in range(n):
for j in range(n):
if puzzle[i][j] > X:
# this cell is the sum of all the surrounding cells
solver.Add(
puzzle[i][j] == solver.Sum([pict[i+a,j+b]
for a in S for b in S
if i + a >=0 and
j + b >=0 and
i + a < n and
j + b < n
])
)
#
# solution and search
#
db = solver.Phase(pict_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
print "Solution:"
while solver.NextSolution():
num_solutions += 1
for i in range(n):
row = [str(pict[i,j].Value()) for j in range(n)]
for j in range(n):
if row[j] == '0':
row[j] = ' '
else:
row[j] = '#'
print "".join(row)
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
#
# Read a problem instance from a file
#
def read_problem(file):
f = open(file, 'r')
n = int(f.readline())
puzzle = []
for i in range(n):
x = f.readline()
row = [0]*n
for j in range(n):
if x[j] == '.':
tmp = -1
else:
tmp = int(x[j])
row[j] = tmp
puzzle.append(row)
return [puzzle, n]
f = open(file, 'r')
n = int(f.readline())
puzzle = []
for i in range(n):
x = f.readline()
row = [0] * n
for j in range(n):
if x[j] == '.':
tmp = -1
else:
tmp = int(x[j])
row[j] = tmp
puzzle.append(row)
return [puzzle, n]
if __name__ == '__main__':
if len(sys.argv) > 1:
file = sys.argv[1]
print 'Problem instance from', file
[puzzle, n] = read_problem(file)
main(puzzle, n)
else:
main()
if len(sys.argv) > 1:
file = sys.argv[1]
print 'Problem instance from', file
[puzzle, n] = read_problem(file)
main(puzzle, n)
else:
main()

View File

@@ -33,9 +33,11 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
@@ -61,115 +63,113 @@ from ortools.constraint_solver import pywrapcp
#
def my_cumulative(solver, s, d, r, b):
# tasks = [i for i in range(len(s))]
tasks = [i for i in range(len(s)) if r[i] > 0 and d[i] > 0]
times_min = min([s[i].Min() for i in tasks])
times_max = max([s[i].Max() + max(d) for i in tasks])
for t in xrange(times_min, times_max+1):
bb = []
for i in tasks:
c1 = solver.IsLessOrEqualCstVar(s[i], t) # s[i] <= t
c2 = solver.IsGreaterCstVar(s[i]+d[i], t) # t < s[i] + d[i]
bb.append(c1*c2*r[i])
solver.Add(solver.Sum(bb) <= b)
# tasks = [i for i in range(len(s))]
tasks = [i for i in range(len(s)) if r[i] > 0 and d[i] > 0]
times_min = min([s[i].Min() for i in tasks])
times_max = max([s[i].Max() + max(d) for i in tasks])
for t in xrange(times_min, times_max + 1):
bb = []
for i in tasks:
c1 = solver.IsLessOrEqualCstVar(s[i], t) # s[i] <= t
c2 = solver.IsGreaterCstVar(s[i] + d[i], t) # t < s[i] + d[i]
bb.append(c1 * c2 * r[i])
solver.Add(solver.Sum(bb) <= b)
# Somewhat experimental:
# This constraint is needed to contrain the upper limit of b.
if not isinstance(b, int):
solver.Add(b <= sum(r))
# Somewhat experimental:
# This constraint is needed to contrain the upper limit of b.
if not isinstance(b, int):
solver.Add(b <= sum(r))
def main():
# Create the solver.
solver = pywrapcp.Solver('Furniture moving')
# Create the solver.
solver = pywrapcp.Solver("Furniture moving")
#
# data
#
n = 4
duration = [30,10,15,15]
demand = [ 3, 1, 3, 2]
upper_limit = 160
#
# data
#
n = 4
duration = [30, 10, 15, 15]
demand = [3, 1, 3, 2]
upper_limit = 160
#
# declare variables
#
start_times = [solver.IntVar(0, upper_limit, 'start_times[%i]'%i) for i in range(n)]
end_times = [solver.IntVar(0, upper_limit*2, 'end_times[%i]'%i) for i in range(n)]
end_time = solver.IntVar(0, upper_limit*2, 'end_time')
#
# declare variables
#
start_times = [
solver.IntVar(0, upper_limit, "start_times[%i]" % i) for i in range(n)]
end_times = [
solver.IntVar(0, upper_limit * 2, "end_times[%i]" % i) for i in range(n)]
end_time = solver.IntVar(0, upper_limit * 2, "end_time")
# number of needed resources, to be minimized
num_resources = solver.IntVar(0, 10, 'num_resources')
# number of needed resources, to be minimized
num_resources = solver.IntVar(0, 10, "num_resources")
#
# constraints
#
for i in range(n):
solver.Add(end_times[i] == start_times[i] + duration[i])
#
# constraints
#
for i in range(n):
solver.Add(end_times[i] == start_times[i] + duration[i])
solver.Add(end_time == solver.Max(end_times))
solver.Add(end_time == solver.Max(end_times))
my_cumulative(solver, start_times, duration, demand, num_resources)
my_cumulative(solver, start_times, duration, demand, num_resources)
#
# Some extra constraints to play with
#
# all tasks must end within an hour
# solver.Add(end_time <= 60)
#
# Some extra constraints to play with
#
# All tasks should start at time 0
# for i in range(n):
# solver.Add(start_times[i] == 0)
## all tasks must end within an hour
# solver.Add(end_time <= 60)
# limitation of the number of people
# solver.Add(num_resources <= 3)
## All tasks should start at time 0
# for i in range(n):
# solver.Add(start_times[i] == 0)
#
# objective
#
# objective = solver.Minimize(end_time, 1)
objective = solver.Minimize(num_resources, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(start_times)
solution.Add(end_times)
solution.Add(end_time)
solution.Add(num_resources)
## limitation of the number of people
# solver.Add(num_resources <= 3)
#
# objective
#
# objective = solver.Minimize(end_time, 1)
objective = solver.Minimize(num_resources, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(start_times)
solution.Add(end_times)
solution.Add(end_time)
solution.Add(num_resources)
db = solver.Phase(start_times,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "num_resources:", num_resources.Value()
print "start_times :", [start_times[i].Value() for i in range(n)]
print "duration :", [duration[i] for i in range(n)]
print "end_times :", [end_times[i].Value() for i in range(n)]
print "end_time :", end_time.Value()
print
solver.EndSearch()
db = solver.Phase(start_times,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "num_resources:", num_resources.Value()
print "start_times :", [start_times[i].Value() for i in range(n)]
print "duration :", [duration[i] for i in range(n)]
print "end_times :", [end_times[i].Value() for i in range(n)]
print "end_time :", end_time.Value()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == "__main__":
main()

View File

@@ -42,7 +42,8 @@
* SICStus: http://hakank.org/sicstus/futoshiki.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -50,77 +51,72 @@ from ortools.constraint_solver import pywrapcp
def main(values, lt):
# Create the solver.
solver = pywrapcp.Solver('Futoshiki problem')
# Create the solver.
solver = pywrapcp.Solver("Futoshiki problem")
#
# data
#
size = len(values)
RANGE = range(size)
NUMQD = range(len(lt))
#
# data
#
size = len(values)
RANGE = range(size)
NUMQD = range(len(lt))
#
# variables
#
field = {}
for i in RANGE:
for j in RANGE:
field[i, j] = solver.IntVar(1, size, "field[%i,%i]" % (i, j))
field_flat = [field[i, j] for i in RANGE for j in RANGE]
#
# variables
#
field = {}
for i in RANGE:
for j in RANGE:
field[i,j] = solver.IntVar(1, size, "field[%i,%i]" % (i,j))
field_flat = [field[i,j] for i in RANGE for j in RANGE]
#
# constraints
#
# set initial values
for row in RANGE:
for col in RANGE:
if values[row][col] > 0:
solver.Add(field[row,col] == values[row][col])
# all rows have to be different
for row in RANGE:
solver.Add(solver.AllDifferent([field[row,col] for col in RANGE]))
# all columns have to be different
#
# constraints
#
# set initial values
for row in RANGE:
for col in RANGE:
solver.Add(solver.AllDifferent([field[row,col] for row in RANGE]))
if values[row][col] > 0:
solver.Add(field[row, col] == values[row][col])
# all rows have to be different
for row in RANGE:
solver.Add(solver.AllDifferent([field[row, col] for col in RANGE]))
# all < constraints are satisfied
# Also: make 0-based
for i in NUMQD:
solver.Add(field[ lt[i][0]-1, lt[i][1]-1 ] <
field[ lt[i][2]-1, lt[i][3]-1 ] )
# all columns have to be different
for col in RANGE:
solver.Add(solver.AllDifferent([field[row, col] for row in RANGE]))
# all < constraints are satisfied
# Also: make 0-based
for i in NUMQD:
solver.Add(field[lt[i][0] - 1, lt[i][1] - 1] <
field[lt[i][2] - 1, lt[i][3] - 1])
#
# search and result
#
db = solver.Phase(field_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# search and result
#
db = solver.Phase(field_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
for i in RANGE:
for j in RANGE:
print field[i,j].Value(),
print
print
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
for i in RANGE:
for j in RANGE:
print field[i, j].Value(),
print
print
solver.EndSearch()
solver.EndSearch()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
#
@@ -146,17 +142,17 @@ values1 = [
# [i1,j1, i2,j2] requires that values[i1,j1] < values[i2,j2]
# Note: 1-based
lt1 = [
[1,2, 1,1],
[1,4, 1,5],
[2,3, 1,3],
[3,3, 2,3],
[3,4, 2,4],
[2,5, 3,5],
[3,2, 4,2],
[4,4, 4,3],
[5,2, 5,1],
[5,4, 5,3],
[5,5, 4,5]]
[1, 2, 1, 1],
[1, 4, 1, 5],
[2, 3, 1, 3],
[3, 3, 2, 3],
[3, 4, 2, 4],
[2, 5, 3, 5],
[3, 2, 4, 2],
[4, 4, 4, 3],
[5, 2, 5, 1],
[5, 4, 5, 3],
[5, 5, 4, 5]]
#
@@ -177,17 +173,17 @@ values2 = [
# Note: 1-based
lt2 = [
[1,2, 1,1],
[1,4, 1,3],
[1,5, 1,4],
[4,4, 4,5],
[5,1, 5,2],
[5,2, 5,3]
]
[1, 2, 1, 1],
[1, 4, 1, 3],
[1, 5, 1, 4],
[4, 4, 4, 5],
[5, 1, 5, 2],
[5, 2, 5, 3]
]
if __name__ == '__main__':
print "Problem 1"
main(values1, lt1)
print "\nProblem 2"
main(values2, lt2)
if __name__ == "__main__":
print "Problem 1"
main(values1, lt1)
print "\nProblem 2"
main(values2, lt2)

View File

@@ -21,13 +21,15 @@
From Taha, Operations Research (8'th edition), page 528.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -40,16 +42,13 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
# data
rows = 3
cols = 3
game = [[3.0, -1.0, -3.0],
[-2.0, 4.0, -1.0],
[-5.0, -6.0, 2.0]
]
[-2.0, 4.0, -1.0],
[-5.0, -6.0, 2.0]]
#
# declare variables
@@ -58,13 +57,13 @@ def main(sol = 'GLPK'):
#
# row player
#
x1 = [solver.NumVar(0, 1, 'x1[%i]' % i )
for i in range(rows)]
x1 = [solver.NumVar(0, 1, 'x1[%i]' % i)
for i in range(rows)]
v = solver.NumVar(-2, 2, 'v')
for i in range(rows):
solver.Add(v - solver.Sum([x1[j]*game[j][i] for j in range(cols)]) <= 0)
solver.Add(v - solver.Sum([x1[j] * game[j][i] for j in range(cols)]) <= 0)
solver.Add(solver.Sum(x1) == 1)
@@ -73,7 +72,7 @@ def main(sol = 'GLPK'):
solver.Solve()
print
print 'row player:';
print 'row player:'
print 'v = ', solver.Objective().Value()
print 'Strategies: '
for i in range(rows):
@@ -81,17 +80,16 @@ def main(sol = 'GLPK'):
print
print
#
# For column player:
#
x2 = [solver.NumVar(0, 1, 'x2[%i]' % i )
for i in range(cols)]
x2 = [solver.NumVar(0, 1, 'x2[%i]' % i)
for i in range(cols)]
v2 = solver.NumVar(-2, 2, 'v2')
for i in range(cols):
solver.Add(v2 - solver.Sum([x2[j]*game[i][j] for j in range(rows)]) >= 0)
solver.Add(v2 - solver.Sum([x2[j] * game[i][j] for j in range(rows)]) >= 0)
solver.Add(solver.Sum(x2) == 1)
@@ -100,14 +98,13 @@ def main(sol = 'GLPK'):
solver.Solve()
print
print 'column player:';
print 'column player:'
print 'v2 = ', solver.Objective().Value()
print 'Strategies: '
for i in range(rows):
print x2[i].SolutionValue(),
print
print
print 'walltime :', solver.WallTime(), 'ms'
print 'iterations:', solver.Iterations()

View File

@@ -23,7 +23,6 @@ of the rule.
"""
from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp
@@ -50,7 +49,7 @@ def main(unused_argv):
solver.Add(marks[0] == 0)
solver.Add(solver.AllDifferent([marks[j] - marks[i]
for i in range(0, size - 1)
for j in range(i +1, size)]))
for j in range(i + 1, size)]))
solver.Add(marks[size - 1] - marks[size - 2] > marks[1] - marks[0])
for i in range(0, size - 2):
@@ -65,7 +64,7 @@ def main(unused_argv):
solver.ASSIGN_MIN_VALUE),
[objective, collector])
for i in range(0, collector.SolutionCount()):
obj_value = collector.Value(i, marks[size -1])
obj_value = collector.Value(i, marks[size - 1])
time = collector.WallTime(i)
branches = collector.Branches(i)
failures = collector.Failures(i)

View File

@@ -33,7 +33,8 @@
* Zinc: http://hakank.org/minizinc/grocery.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -44,51 +45,51 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Grocery')
# Create the solver.
solver = pywrapcp.Solver("Grocery")
#
# data
#
n = 4
c = 711
#
# data
#
n = 4
c = 711
#
# declare variables
#
item = [solver.IntVar(0, c, "item[%i]" % i) for i in range(n)]
#
# declare variables
#
item = [solver.IntVar(0, c, "item[%i]" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.Sum(item) == c)
solver.Add(reduce(lambda x, y: x * y, item) == c * 100**3)
#
# constraints
#
solver.Add(solver.Sum(item) == c)
solver.Add(reduce(lambda x, y: x * y, item) == c * 100 ** 3)
# symmetry breaking
for i in range(1,n):
solver.Add(item[i-1] < item[i])
# symmetry breaking
for i in range(1, n):
solver.Add(item[i - 1] < item[i])
#
# search and result
#
db = solver.Phase(item,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "item:", [item[i].Value() for i in range(n)]
print
num_solutions += 1
solver.EndSearch()
#
# search and result
#
db = solver.Phase(item,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "item:", [item[i].Value() for i in range(n)]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
if __name__ == '__main__':
main()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == "__main__":
main()

View File

@@ -38,7 +38,8 @@
(and more elegant) model: hidato_table.py .
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -46,22 +47,22 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
#
# Simple problem
#
# r = 3
# c = r
# puzzle = [
# [6,0,9],
# [0,2,8],
# [1,0,0]
# ]
#
# data
#
#
# Simple problem
#
# r = 3
# c = r
# puzzle = [
# [6,0,9],
# [0,2,8],
# [1,0,0]
# ]
# r = 7
@@ -76,34 +77,33 @@ def main():
# [0, 0, 0,14, 0, 0, 0]
# ]
# Problems from the book:
# Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles"
# Problems from the book:
# Gyora Bededek: "Hidato: 2000 Pure Logic Puzzles"
# Problem 1 (Practice)
# r = 5
# c = r
# puzzle = [
# [ 0, 0,20, 0, 0],
# [ 0, 0, 0,16,18],
# [22, 0,15, 0, 0],
# [23, 0, 1,14,11],
# [ 0,25, 0, 0,12],
# ]
# Problem 1 (Practice)
# r = 5
# c = r
# puzzle = [
# [ 0, 0,20, 0, 0],
# [ 0, 0, 0,16,18],
# [22, 0,15, 0, 0],
# [23, 0, 1,14,11],
# [ 0,25, 0, 0,12],
# ]
# # problem 2 (Practice)
r = 5
c = r
puzzle= [
[0, 0, 0, 0,14],
[0,18,12, 0, 0],
[0, 0,17, 4, 5],
[0, 0, 7, 0, 0],
[9, 8,25, 1, 0],
];
r = 5
c = r
puzzle = [
[0, 0, 0, 0, 14],
[0, 18, 12, 0, 0],
[0, 0, 17, 4, 5],
[0, 0, 7, 0, 0],
[9, 8, 25, 1, 0],
]
# problem 3 (Beginner)
# problem 3 (Beginner)
# r = 6
# c = r
# puzzle = [
@@ -115,9 +115,8 @@ def main():
# [35,36, 0,10, 0, 0]
# ];
# Problem 15 (Intermediate)
# Note: This takes very long time to solve...
# Problem 15 (Intermediate)
# Note: This takes very long time to solve...
# r = 8
# c = r
# puzzle = [
@@ -131,121 +130,111 @@ def main():
# [28,30, 0,35, 0, 0, 0, 0]
# ]
print_game(puzzle, r, c)
print_game(puzzle, r,c)
#
# declare variables
#
x = {}
for i in range(r):
for j in range(c):
x[(i, j)] = solver.IntVar(1, r * c, "dice(%i,%i)" % (i, j))
x_flat = [x[(i, j)] for i in range(r) for j in range(c)]
#
# declare variables
#
x = {}
for i in range(r):
for j in range(c):
x[(i,j)] = solver.IntVar(1,r*c, 'dice(%i,%i)' % (i, j))
x_flat = [x[(i,j)] for i in range(r) for j in range(c)]
#
# constraints
#
solver.Add(solver.AllDifferent(x_flat))
#
# Fill in the clues
#
for i in range(r):
for j in range(c):
if puzzle[i][j] > 0:
solver.Add(x[(i, j)] == puzzle[i][j])
# From the numbers k = 1 to r*c-1, find this position,
# and then the position of k+1
for k in range(1, r * c):
i = solver.IntVar(0, r)
j = solver.IntVar(0, c)
a = solver.IntVar(-1, 1)
b = solver.IntVar(-1, 1)
#
# constraints
#
solver.Add(solver.AllDifferent(x_flat))
# 1) First: fix "this" k
# 2) and then find the position of the next value (k+1)
# solver.Add(k == x[(i,j)])
solver.Add(k == solver.Element(x_flat, i * c + j))
# solver.Add(k + 1 == x[(i+a,j+b)])
solver.Add(k + 1 == solver.Element(x_flat, (i + a) * c + (j + b)))
#
# Fill in the clues
#
for i in range(r):
for j in range(c):
if puzzle[i][j] > 0:
solver.Add(x[(i,j)] == puzzle[i][j])
solver.Add(i + a >= 0)
solver.Add(j + b >= 0)
solver.Add(i + a < r)
solver.Add(j + b < c)
# solver.Add(((a != 0) | (b != 0)))
a_nz = solver.BoolVar()
b_nz = solver.BoolVar()
solver.Add(a_nz == solver.IsDifferentCstVar(a, 0))
solver.Add(b_nz == solver.IsDifferentCstVar(b, 0))
solver.Add(a_nz + b_nz >= 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
# From the numbers k = 1 to r*c-1, find this position,
# and then the position of k+1
for k in range(1,r*c):
i = solver.IntVar(0,r)
j = solver.IntVar(0,c)
a = solver.IntVar(-1,1)
b = solver.IntVar(-1,1)
# 1) First: fix "this" k
# 2) and then find the position of the next value (k+1)
# solver.Add(k == x[(i,j)])
solver.Add(k == solver.Element(x_flat, i*c+j))
# solver.Add(k + 1 == x[(i+a,j+b)])
solver.Add(k + 1 == solver.Element(x_flat, (i+a)*c+(j+b)))
solver.Add(i+a >= 0)
solver.Add(j+b >= 0)
solver.Add(i+a < r)
solver.Add(j+b < c)
# solver.Add(((a != 0) | (b != 0)))
a_nz = solver.BoolVar()
b_nz = solver.BoolVar()
solver.Add(a_nz == solver.IsDifferentCstVar(a,0))
solver.Add(b_nz == solver.IsDifferentCstVar(b,0))
solver.Add(a_nz + b_nz >= 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
# db: DecisionBuilder
db = solver.Phase(x_flat,
#solver.INT_VAR_DEFAULT
#solver.INT_VAR_SIMPLE
solver.CHOOSE_FIRST_UNBOUND
# solver.CHOOSE_RANDOM
#solver.CHOOSE_MIN_SIZE_LOWEST_MIN
#solver.CHOOSE_MIN_SIZE_HIGHEST_MIN
#solver.CHOOSE_MIN_SIZE_LOWEST_MAX
#solver.CHOOSE_MIN_SIZE_HIGHEST_MAX
#solver.CHOOSE_PATH
,
# solver.INT_VALUE_DEFAULT
# solver.INT_VALUE_SIMPLE
solver.ASSIGN_MIN_VALUE
#solver.ASSIGN_MAX_VALUE
#solver.ASSIGN_RANDOM_VALUE
#solver.ASSIGN_CENTER_VALUE
)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nSolution:", num_solutions
print_board(x, r, c)
print
solver.EndSearch()
# db: DecisionBuilder
db = solver.Phase(x_flat,
# solver.INT_VAR_DEFAULT
# solver.INT_VAR_SIMPLE
# solver.CHOOSE_RANDOM
# solver.CHOOSE_MIN_SIZE_LOWEST_MIN
# solver.CHOOSE_MIN_SIZE_HIGHEST_MIN
# solver.CHOOSE_MIN_SIZE_LOWEST_MAX
# solver.CHOOSE_MIN_SIZE_HIGHEST_MAX
# solver.CHOOSE_PATH
solver.CHOOSE_FIRST_UNBOUND,
# solver.INT_VALUE_DEFAULT
# solver.INT_VALUE_SIMPLE
# solver.ASSIGN_MAX_VALUE
# solver.ASSIGN_RANDOM_VALUE
# solver.ASSIGN_CENTER_VALUE
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "\nSolution:", num_solutions
print_board(x, r, c)
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
def print_board(x, rows, cols):
for i in range(rows):
for j in range(cols):
print "% 2s" % x[i,j].Value(),
print ''
for i in range(rows):
for j in range(cols):
print "% 2s" % x[i, j].Value(),
print ""
def print_game(game, rows, cols):
for i in range(rows):
for j in range(cols):
print "% 2s" % game[i][j],
print ''
for i in range(rows):
for j in range(cols):
print "% 2s" % game[i][j],
print ""
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -101,7 +101,7 @@ def Solve(model):
[9, 8, 25, 1, 0]]
elif model == 5:
# problem 3 (Beginner)
# problem 3 (Beginner)
puzzle = [[0, 26, 0, 0, 0, 18],
[0, 0, 27, 0, 0, 19],
[31, 23, 0, 0, 14, 0],
@@ -194,7 +194,7 @@ def PrintMatrix(game):
rows = len(game)
cols = len(game[0])
for i in range(rows):
line = ""
line = ''
for j in range(cols):
if game[i][j] == 0:
line += ' .'

View File

@@ -24,7 +24,6 @@ jobs. This is called the makespan.
"""
from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp

View File

@@ -42,7 +42,8 @@
* Gecpde: http://hakank.org/gecode/just_forgotten.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -50,69 +51,68 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Just forgotten')
# Create the solver.
solver = pywrapcp.Solver("Just forgotten")
#
# data
#
rows = 4
cols = 10
# The four tries
a = [[9,4,6,2,1,5,7,8,3,0],
[8,6,0,4,3,9,1,2,5,7],
[1,6,4,0,2,9,7,8,5,3],
[6,8,2,4,3,1,9,0,7,5]]
#
# data
#
rows = 4
cols = 10
# The four tries
a = [[9, 4, 6, 2, 1, 5, 7, 8, 3, 0],
[8, 6, 0, 4, 3, 9, 1, 2, 5, 7],
[1, 6, 4, 0, 2, 9, 7, 8, 5, 3],
[6, 8, 2, 4, 3, 1, 9, 0, 7, 5]]
#
# variables
#
x = [solver.IntVar(0, 9, "x[%i]" % j) for j in range(cols)]
#
# variables
#
x = [solver.IntVar(0, 9, "x[%i]" % j) for j in range(cols)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
for r in range(rows):
b = [solver.IsEqualCstVar(x[c], a[r][c]) for c in range(cols)]
solver.Add(solver.Sum(b) == 4)
for r in range(rows):
b = [solver.IsEqualCstVar(x[c], a[r][c]) for c in range(cols)]
solver.Add(solver.Sum(b) == 4)
#
# search and result
#
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
#
# search and result
#
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
xval = [x[j].Value() for j in range(cols)]
print "Account number:"
for j in range(cols):
print "%i " % xval[j],
print
print "\nThe four tries, where '!' represents a correct digit:"
for i in range(rows):
for j in range(cols):
check = " "
if a[i][j] == xval[j]:
check = "!"
print "%i%s" % (a[i][j], check),
print
print
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
xval = [x[j].Value() for j in range(cols)]
print "Account number:"
for j in range(cols):
print "%i " % xval[j],
print
print "\nThe four tries, where '!' represents a correct digit:"
for i in range(rows):
for j in range(cols):
check = " "
if a[i][j] == xval[j]:
check = "!"
print "%i%s" % (a[i][j], check),
print
print
print
solver.EndSearch()
solver.EndSearch()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -52,7 +52,8 @@
* Gecode: http://www.hakank.org/gecode/kenken2.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -63,141 +64,140 @@ from ortools.constraint_solver import pywrapcp
# Ensure that the sum of the segments
# in cc == res
#
def calc(cc, x, res):
solver = x.values()[0].solver()
solver = x.values()[0].solver()
# ensure that the values are positive
for i in cc:
solver.Add(x[i[0]-1, i[1]-1] >= 1)
# ensure that the values are positive
for i in cc:
solver.Add(x[i[0] - 1, i[1] - 1] >= 1)
# sum the numbers
solver.Add(solver.Sum([x[i[0]-1,i[1]-1] for i in cc]) == res)
# sum the numbers
solver.Add(solver.Sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res)
def main():
# Create the solver.
solver = pywrapcp.Solver('Kakuro')
# Create the solver.
solver = pywrapcp.Solver("Kakuro")
#
# data
#
#
# data
#
# size of matrix
n = 7
# size of matrix
n = 7
# segments
# [sum, [segments]]
# Note: 1-based
problem = [
[16, [1,1],[1,2]],
[24, [1,5],[1,6],[1,7]],
[17, [2,1],[2,2]],
[29, [2,4],[2,5],[2,6],[2,7]],
[35, [3,1],[3,2],[3,3],[3,4],[3,5]],
[ 7, [4,2],[4,3]],
[ 8, [4,5],[4,6]],
[16, [5,3],[5,4],[5,5],[5,6],[5,7]],
[21, [6,1],[6,2],[6,3],[6,4]],
[ 5, [6,6],[6,7]],
[ 6, [7,1],[7,2],[7,3]],
[ 3, [7,6],[7,7]],
# segments
# [sum, [segments]]
# Note: 1-based
problem = [
[16, [1, 1], [1, 2]],
[24, [1, 5], [1, 6], [1, 7]],
[17, [2, 1], [2, 2]],
[29, [2, 4], [2, 5], [2, 6], [2, 7]],
[35, [3, 1], [3, 2], [3, 3], [3, 4], [3, 5]],
[7, [4, 2], [4, 3]],
[8, [4, 5], [4, 6]],
[16, [5, 3], [5, 4], [5, 5], [5, 6], [5, 7]],
[21, [6, 1], [6, 2], [6, 3], [6, 4]],
[5, [6, 6], [6, 7]],
[6, [7, 1], [7, 2], [7, 3]],
[3, [7, 6], [7, 7]],
[23, [1,1],[2,1],[3,1]],
[30, [1,2],[2,2],[3,2],[4,2]],
[27, [1,5],[2,5],[3,5],[4,5],[5,5]],
[12, [1,6],[2,6]],
[16, [1,7],[2,7]],
[17, [2,4],[3,4]],
[15, [3,3],[4,3],[5,3],[6,3],[7,3]],
[12, [4,6],[5,6],[6,6],[7,6]],
[ 7, [5,4],[6,4]],
[ 7, [5,7],[6,7],[7,7]],
[11, [6,1],[7,1]],
[10, [6,2],[7,2]]
]
[23, [1, 1], [2, 1], [3, 1]],
[30, [1, 2], [2, 2], [3, 2], [4, 2]],
[27, [1, 5], [2, 5], [3, 5], [4, 5], [5, 5]],
[12, [1, 6], [2, 6]],
[16, [1, 7], [2, 7]],
[17, [2, 4], [3, 4]],
[15, [3, 3], [4, 3], [5, 3], [6, 3], [7, 3]],
[12, [4, 6], [5, 6], [6, 6], [7, 6]],
[7, [5, 4], [6, 4]],
[7, [5, 7], [6, 7], [7, 7]],
[11, [6, 1], [7, 1]],
[10, [6, 2], [7, 2]]
]
num_p = len(problem)
num_p = len(problem)
# The blanks
# Note: 1-based
blanks = [
[1,3], [1,4],
[2,3],
[3,6], [3,7],
[4,1], [4,4], [4,7],
[5,1], [5,2],
[6,5],
[7,4], [7,5]
]
num_blanks = len(blanks)
# The blanks
# Note: 1-based
blanks = [
[1, 3], [1, 4],
[2, 3],
[3, 6], [3, 7],
[4, 1], [4, 4], [4, 7],
[5, 1], [5, 2],
[6, 5],
[7, 4], [7, 5]
]
num_blanks = len(blanks)
#
# variables
#
#
# variables
#
# the set
x = {}
# the set
x = {}
for i in range(n):
for j in range(n):
x[i, j] = solver.IntVar(0, 9, "x[%i,%i]" % (i, j))
x_flat = [x[i, j] for i in range(n) for j in range(n)]
#
# constraints
#
# fill the blanks with 0
for i in range(num_blanks):
solver.Add(x[blanks[i][0] - 1, blanks[i][1] - 1] == 0)
for i in range(num_p):
segment = problem[i][1::]
res = problem[i][0]
# sum this segment
calc(segment, x, res)
# all numbers in this segment must be distinct
segment = [x[p[0] - 1, p[1] - 1] for p in segment]
solver.Add(solver.AllDifferent(segment))
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
x[i,j] = solver.IntVar(0, 9, 'x[%i,%i]' % (i,j))
x_flat = [x[i,j] for i in range(n) for j in range(n)]
#
# constraints
#
# fill the blanks with 0
for i in range(num_blanks):
solver.Add(x[blanks[i][0]-1,blanks[i][1]-1]==0)
for i in range(num_p):
segment = problem[i][1::]
res = problem[i][0]
# sum this segment
calc(segment, x, res)
# all numbers in this segment must be distinct
segment = [x[p[0]-1, p[1]-1] for p in segment]
solver.Add(solver.AllDifferent(segment))
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
val = x[i,j].Value()
if val > 0:
print val,
else:
print " ",
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
val = x[i, j].Value()
if val > 0:
print val,
else:
print " ",
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -53,7 +53,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -64,141 +65,140 @@ from ortools.constraint_solver import pywrapcp
# Ensure that the sum of the segments
# in cc == res
#
def calc(cc, x, res):
solver = x.values()[0].solver()
solver = x.values()[0].solver()
if len(cc) == 2:
if len(cc) == 2:
# for two operands there may be
# a lot of variants
# for two operands there may be
# a lot of variants
c00, c01 = cc[0]
c10, c11 = cc[1]
a = x[c00-1, c01-1]
b = x[c10-1, c11-1]
c00, c01 = cc[0]
c10, c11 = cc[1]
a = x[c00 - 1, c01 - 1]
b = x[c10 - 1, c11 - 1]
r1 = solver.IsEqualCstVar(a + b, res)
r2 = solver.IsEqualCstVar(a * b, res)
r3 = solver.IsEqualVar(a * res, b)
r4 = solver.IsEqualVar(b * res, a)
r5 = solver.IsEqualCstVar(a - b, res)
r6 = solver.IsEqualCstVar(b - a, res)
solver.Add(r1+r2+r3+r4+r5+r6 >= 1)
r1 = solver.IsEqualCstVar(a + b, res)
r2 = solver.IsEqualCstVar(a * b, res)
r3 = solver.IsEqualVar(a * res, b)
r4 = solver.IsEqualVar(b * res, a)
r5 = solver.IsEqualCstVar(a - b, res)
r6 = solver.IsEqualCstVar(b - a, res)
solver.Add(r1 + r2 + r3 + r4 + r5 + r6 >= 1)
else:
else:
# res is either sum or product of the segment
# res is either sum or product of the segment
xx = [x[i[0]-1,i[1]-1] for i in cc]
xx = [x[i[0] - 1, i[1] - 1] for i in cc]
# Sum
# # SumEquality don't work:
# this_sum = solver.SumEquality(xx, res)
this_sum = solver.IsEqualCstVar(solver.Sum(xx), res)
# Sum
# # SumEquality don't work:
# this_sum = solver.SumEquality(xx, res)
this_sum = solver.IsEqualCstVar(solver.Sum(xx), res)
# Product
# # Prod (or MakeProd) don't work:
# this_prod = solver.IsEqualCstVar(solver.Prod(xx), res)
this_prod = solver.IsEqualCstVar(reduce(lambda a, b: a*b, xx), res)
solver.Add(this_sum + this_prod >= 1)
# Product
# # Prod (or MakeProd) don't work:
# this_prod = solver.IsEqualCstVar(solver.Prod(xx), res)
this_prod = solver.IsEqualCstVar(reduce(lambda a, b: a * b, xx), res)
solver.Add(this_sum + this_prod >= 1)
def main():
# Create the solver.
solver = pywrapcp.Solver('KenKen')
# Create the solver.
solver = pywrapcp.Solver("KenKen")
#
# data
#
#
# data
#
# size of matrix
n = 6
# size of matrix
n = 6
# For a better view of the problem, see
# http://en.wikipedia.org/wiki/File:KenKenProblem.svg
# For a better view of the problem, see
# http://en.wikipedia.org/wiki/File:KenKenProblem.svg
# hints
# [sum, [segments]]
# Note: 1-based
problem = [
[11, [[1, 1], [2, 1]]],
[2, [[1, 2], [1, 3]]],
[20, [[1, 4], [2, 4]]],
[6, [[1, 5], [1, 6], [2, 6], [3, 6]]],
[3, [[2, 2], [2, 3]]],
[3, [[2, 5], [3, 5]]],
[240, [[3, 1], [3, 2], [4, 1], [4, 2]]],
[6, [[3, 3], [3, 4]]],
[6, [[4, 3], [5, 3]]],
[7, [[4, 4], [5, 4], [5, 5]]],
[30, [[4, 5], [4, 6]]],
[6, [[5, 1], [5, 2]]],
[9, [[5, 6], [6, 6]]],
[8, [[6, 1], [6, 2], [6, 3]]],
[2, [[6, 4], [6, 5]]]]
# hints
# [sum, [segments]]
# Note: 1-based
problem = [
[ 11, [[1,1], [2,1]]],
[ 2, [[1,2], [1,3]]],
[ 20, [[1,4], [2,4]]],
[ 6, [[1,5], [1,6], [2,6], [3,6]]],
[ 3, [[2,2], [2,3]]],
[ 3, [[2,5], [3,5]]],
[240, [[3,1], [3,2], [4,1], [4,2]]],
[ 6, [[3,3], [3,4]]],
[ 6, [[4,3], [5,3]]],
[ 7, [[4,4], [5,4], [5,5]]],
[ 30, [[4,5], [4,6]]],
[ 6, [[5,1], [5,2]]],
[ 9, [[5,6], [6,6]]],
[ 8, [[6,1], [6,2], [6,3]]],
[ 2, [[6,4], [6,5]]]]
num_p = len(problem)
num_p = len(problem)
#
# variables
#
#
# variables
#
# the set
x = {}
for i in range(n):
for j in range(n):
x[i, j] = solver.IntVar(1, n, "x[%i,%i]" % (i, j))
# the set
x = {}
x_flat = [x[i, j] for i in range(n) for j in range(n)]
#
# constraints
#
# all rows and columns must be unique
for i in range(n):
row = [x[i, j] for j in range(n)]
solver.Add(solver.AllDifferent(row))
col = [x[j, i] for j in range(n)]
solver.Add(solver.AllDifferent(col))
# calculate the segments
for (res, segment) in problem:
calc(segment, x, res)
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
x[i,j] = solver.IntVar(1, n, 'x[%i,%i]' % (i,j))
x_flat = [x[i,j] for i in range(n) for j in range(n)]
#
# constraints
#
# all rows and columns must be unique
for i in range(n):
row = [x[i,j] for j in range(n)]
solver.Add(solver.AllDifferent(row))
col = [x[j,i] for j in range(n)]
solver.Add(solver.AllDifferent(col))
# calculate the segments
for (res, segment) in problem:
calc(segment, x, res)
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
print x[i,j].Value(),
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
print x[i, j].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -64,7 +64,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -75,128 +76,128 @@ from ortools.constraint_solver import pywrapcp
# Ensure that the sum of the segments
# in cc == res
#
def calc(cc, x, res):
solver = x.values()[0].solver()
# sum the numbers
solver.Add(solver.Sum([x[i[0]-1,i[1]-1] for i in cc]) == res)
solver = x.values()[0].solver()
# sum the numbers
solver.Add(solver.Sum([x[i[0] - 1, i[1] - 1] for i in cc]) == res)
def main():
# Create the solver.
solver = pywrapcp.Solver('Killer Sudoku')
# Create the solver.
solver = pywrapcp.Solver("Killer Sudoku")
#
# data
#
#
# data
#
# size of matrix
n = 9
# size of matrix
n = 9
# For a better view of the problem, see
# http://en.wikipedia.org/wiki/File:Killersudoku_color.svg
# For a better view of the problem, see
# http://en.wikipedia.org/wiki/File:Killersudoku_color.svg
# hints
# [sum, [segments]]
# Note: 1-based
problem = [
[ 3, [[1,1], [1,2]]],
[15, [[1,3], [1,4], [1,5]]],
[22, [[1,6], [2,5], [2,6], [3,5]]],
[ 4, [[1,7], [2,7]]],
[16, [[1,8], [2,8]]],
[15, [[1,9], [2,9], [3,9], [4,9]]],
[25, [[2,1], [2,2], [3,1], [3,2]]],
[17, [[2,3], [2,4]]],
[ 9, [[3,3], [3,4], [4,4]]],
[ 8, [[3,6], [4,6],[5,6]]],
[20, [[3,7], [3,8],[4,7]]],
[ 6, [[4,1], [5,1]]],
[14, [[4,2], [4,3]]],
[17, [[4,5], [5,5],[6,5]]],
[17, [[4,8], [5,7],[5,8]]],
[13, [[5,2], [5,3],[6,2]]],
[20, [[5,4], [6,4],[7,4]]],
[12, [[5,9], [6,9]]],
[27, [[6,1], [7,1],[8,1],[9,1]]],
[ 6, [[6,3], [7,2],[7,3]]],
[20, [[6,6], [7,6], [7,7]]],
[ 6, [[6,7], [6,8]]],
[10, [[7,5], [8,4],[8,5],[9,4]]],
[14, [[7,8], [7,9],[8,8],[8,9]]],
[ 8, [[8,2], [9,2]]],
[16, [[8,3], [9,3]]],
[15, [[8,6], [8,7]]],
[13, [[9,5], [9,6],[9,7]]],
[17, [[9,8], [9,9]]]]
# hints
# [sum, [segments]]
# Note: 1-based
problem = [
[3, [[1, 1], [1, 2]]],
[15, [[1, 3], [1, 4], [1, 5]]],
[22, [[1, 6], [2, 5], [2, 6], [3, 5]]],
[4, [[1, 7], [2, 7]]],
[16, [[1, 8], [2, 8]]],
[15, [[1, 9], [2, 9], [3, 9], [4, 9]]],
[25, [[2, 1], [2, 2], [3, 1], [3, 2]]],
[17, [[2, 3], [2, 4]]],
[9, [[3, 3], [3, 4], [4, 4]]],
[8, [[3, 6], [4, 6], [5, 6]]],
[20, [[3, 7], [3, 8], [4, 7]]],
[6, [[4, 1], [5, 1]]],
[14, [[4, 2], [4, 3]]],
[17, [[4, 5], [5, 5], [6, 5]]],
[17, [[4, 8], [5, 7], [5, 8]]],
[13, [[5, 2], [5, 3], [6, 2]]],
[20, [[5, 4], [6, 4], [7, 4]]],
[12, [[5, 9], [6, 9]]],
[27, [[6, 1], [7, 1], [8, 1], [9, 1]]],
[6, [[6, 3], [7, 2], [7, 3]]],
[20, [[6, 6], [7, 6], [7, 7]]],
[6, [[6, 7], [6, 8]]],
[10, [[7, 5], [8, 4], [8, 5], [9, 4]]],
[14, [[7, 8], [7, 9], [8, 8], [8, 9]]],
[8, [[8, 2], [9, 2]]],
[16, [[8, 3], [9, 3]]],
[15, [[8, 6], [8, 7]]],
[13, [[9, 5], [9, 6], [9, 7]]],
[17, [[9, 8], [9, 9]]]]
#
# variables
#
#
# variables
#
# the set
x = {}
# the set
x = {}
for i in range(n):
for j in range(n):
x[i, j] = solver.IntVar(1, n, "x[%i,%i]" % (i, j))
x_flat = [x[i, j] for i in range(n) for j in range(n)]
#
# constraints
#
# all rows and columns must be unique
for i in range(n):
row = [x[i, j] for j in range(n)]
solver.Add(solver.AllDifferent(row))
col = [x[j, i] for j in range(n)]
solver.Add(solver.AllDifferent(col))
# cells
for i in range(2):
for j in range(2):
cell = [x[r, c]
for r in range(i * 3, i * 3 + 3)
for c in range(j * 3, j * 3 + 3)]
solver.Add(solver.AllDifferent(cell))
# calculate the segments
for (res, segment) in problem:
calc(segment, x, res)
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
x[i,j] = solver.IntVar(1, n, 'x[%i,%i]' % (i,j))
x_flat = [x[i,j] for i in range(n) for j in range(n)]
#
# constraints
#
# all rows and columns must be unique
for i in range(n):
row = [x[i,j] for j in range(n)]
solver.Add(solver.AllDifferent(row))
col = [x[j,i] for j in range(n)]
solver.Add(solver.AllDifferent(col))
# cells
for i in range(2):
for j in range(2):
cell = [x[r,c]
for r in range(i*3,i*3+3)
for c in range(j*3,j*3+3)]
solver.Add(solver.AllDifferent(cell));
# calculate the segments
for (res, segment) in problem:
calc(segment, x, res)
#
# search and solution
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
for i in range(n):
for j in range(n):
print x[i,j].Value(),
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
print x[i, j].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -15,7 +15,6 @@
"""Bi-dimensional knapsack problem."""
from google.apputils import app
import gflags
from ortools.algorithms import pywrapknapsack_solver

View File

@@ -19,78 +19,76 @@
Simple knapsack problem.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def knapsack(solver, values, weights, n):
z = solver.IntVar(0, 10000)
x = [solver.IntVar(0,1,"x(%i)"%i) for i in range(len(values))]
solver.Add(z >= 0)
solver.Add(z == solver.ScalProd(x, values))
solver.Add(solver.ScalProd(x, weights) <= n)
return [x, z]
def knapsack(solver, values, weights, n):
z = solver.IntVar(0, 10000)
x = [solver.IntVar(0, 1, "x(%i)" % i) for i in range(len(values))]
solver.Add(z >= 0)
solver.Add(z == solver.ScalProd(x, values))
solver.Add(solver.ScalProd(x, weights) <= n)
return [x, z]
def main(values, weights, n):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
print "values:", values
print "weights:", weights
print "n:", n
#
# data
#
print "values:", values
print "weights:", weights
print "n:", n
print
# declare variables
#
# constraints
#
[x, z] = knapsack(solver, values, weights, n)
# objective
objective = solver.Maximize(z, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(z)
# db: DecisionBuilder
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "x:", [x[i].Value() for i in range(len(values))]
print "z:", z.Value()
print
num_solutions += 1
solver.EndSearch()
# declare variables
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
#
# constraints
#
[x, z] = knapsack(solver, values, weights, n)
# objective
objective = solver.Maximize(z,1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(z)
# db: DecisionBuilder
db = solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db,[objective])
num_solutions = 0
while solver.NextSolution():
print "x:", [x[i].Value() for i in range(len(values))]
print "z:", z.Value()
print
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
values = [15, 100, 90, 60, 40, 15, 10, 1, 12, 12, 100]
weights = [ 2, 20, 20, 30, 40, 30, 60, 10, 21, 12, 2]
values = [15, 100, 90, 60, 40, 15, 10, 1, 12, 12, 100]
weights = [2, 20, 20, 30, 40, 30, 60, 10, 21, 12, 2]
n = 102
if __name__ == '__main__':
main( values, weights, n)
if __name__ == "__main__":
main(values, weights, n)

View File

@@ -19,12 +19,14 @@
From the OPL model knapsack.mod
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -35,10 +37,9 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
@@ -48,15 +49,15 @@ def main(sol = 'GLPK'):
items = range(nb_items)
resources = range(nb_resources)
capacity = [ 18209, 7692, 1333, 924, 26638, 61188, 13360 ]
value = [ 96, 76, 56, 11, 86, 10, 66, 86, 83, 12, 9, 81 ]
use = [[ 19, 1, 10, 1, 1, 14, 152, 11, 1, 1, 1, 1 ],
[ 0, 4, 53, 0, 0, 80, 0, 4, 5, 0, 0, 0 ],
[ 4, 660, 3, 0, 30, 0, 3, 0, 4, 90, 0, 0],
[ 7, 0, 18, 6, 770, 330, 7, 0, 0, 6, 0, 0],
[ 0, 20, 0, 4, 52, 3, 0, 0, 0, 5, 4, 0],
[ 0, 0, 40, 70, 4, 63, 0, 0, 60, 0, 4, 0],
[ 0, 32, 0, 0, 0, 5, 0, 3, 0, 660, 0, 9]]
capacity = [18209, 7692, 1333, 924, 26638, 61188, 13360]
value = [96, 76, 56, 11, 86, 10, 66, 86, 83, 12, 9, 81]
use = [[19, 1, 10, 1, 1, 14, 152, 11, 1, 1, 1, 1],
[0, 4, 53, 0, 0, 80, 0, 4, 5, 0, 0, 0],
[4, 660, 3, 0, 30, 0, 3, 0, 4, 90, 0, 0],
[7, 0, 18, 6, 770, 330, 7, 0, 0, 6, 0, 0],
[0, 20, 0, 4, 52, 3, 0, 0, 0, 5, 4, 0],
[0, 0, 40, 70, 4, 63, 0, 0, 60, 0, 4, 0],
[0, 32, 0, 0, 0, 5, 0, 3, 0, 660, 0, 9]]
max_value = max(capacity)
@@ -65,7 +66,6 @@ def main(sol = 'GLPK'):
#
take = [solver.IntVar(0, max_value, 'take[%i]' % j) for j in items]
# total cost, to be maximized
z = solver.Sum([value[i] * take[i] for i in items])
@@ -79,7 +79,6 @@ def main(sol = 'GLPK'):
# objective
objective = solver.Maximize(z)
#
# solution and search
#
@@ -93,7 +92,6 @@ def main(sol = 'GLPK'):
print int(take[i].SolutionValue()),
print
print
print 'walltime :', solver.WallTime(), 'ms'
if sol == 'CBC':

View File

@@ -44,7 +44,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -52,94 +53,94 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Labeled dice')
# Create the solver.
solver = pywrapcp.Solver("Labeled dice")
#
# data
#
n = 4
m = 24
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y = range(m)
letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","Y"]
#
# data
#
n = 4
m = 24
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, Y = (
range(m))
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "Y"]
num_words = 13
words = [
[B,U,O,Y],
[C,A,V,E],
[C,E,L,T],
[F,L,U,B],
[F,O,R,K],
[H,E,M,P],
[J,U,D,Y],
[J,U,N,K],
[L,I,M,N],
[Q,U,I,P],
[S,W,A,G],
[V,I,S,A],
[W,I,S,H]
]
num_words = 13
words = [
[B, U, O, Y],
[C, A, V, E],
[C, E, L, T],
[F, L, U, B],
[F, O, R, K],
[H, E, M, P],
[J, U, D, Y],
[J, U, N, K],
[L, I, M, N],
[Q, U, I, P],
[S, W, A, G],
[V, I, S, A],
[W, I, S, H]
]
#
# declare variables
#
dice = [solver.IntVar(0, n-1, 'dice[%i]'%i) for i in range(m)]
#
# declare variables
#
dice = [solver.IntVar(0, n - 1, "dice[%i]" % i) for i in range(m)]
#
# constraints
#
#
# constraints
#
# the letters in a word must be on a different die
# the letters in a word must be on a different die
for i in range(num_words):
solver.Add(solver.AllDifferent([dice[words[i][j]] for j in range(n)]))
# there must be exactly 6 letters of each die
for i in range(n):
b = [solver.IsEqualCstVar(dice[j], i) for j in range(m)]
solver.Add(solver.Sum(b) == 6)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(dice)
db = solver.Phase(dice,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
# print "dice:", [(letters[i],dice[i].Value()) for i in range(m)]
for d in range(n):
print "die %i:" % d,
for i in range(m):
if dice[i].Value() == d:
print letters[i],
print
print "The words with the cube label:"
for i in range(num_words):
solver.Add(solver.AllDifferent([dice[words[i][j]] for j in range(n)]))
# there must be exactly 6 letters of each die
for i in range(n):
b = [solver.IsEqualCstVar(dice[j], i) for j in range(m)]
solver.Add(solver.Sum(b) == 6)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(dice)
db = solver.Phase(dice,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# result
#
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
# print "dice:", [(letters[i],dice[i].Value()) for i in range(m)]
for d in range(n):
print "die %i:" % d,
for i in range(m):
if dice[i].Value() == d:
print letters[i],
print
print "The words with the cube label:"
for i in range(num_words):
for j in range(n):
print "%s (%i)" % (letters[words[i][j]], dice[words[i][j]].Value()),
print
print
solver.EndSearch()
for j in range(n):
print "%s (%i)" % (letters[words[i][j]], dice[words[i][j]].Value()),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == '__main__':
main()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
if __name__ == "__main__":
main()

View File

@@ -41,7 +41,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -52,64 +53,63 @@ from ortools.constraint_solver import pywrapcp
def main(k=8, num_sol=0):
# Create the solver.
solver = pywrapcp.Solver('Langford')
# Create the solver.
solver = pywrapcp.Solver("Langford")
#
# data
#
print "k:", k
p = range(2*k)
#
# data
#
print "k:", k
p = range(2 * k)
#
# declare variables
#
position = [solver.IntVar(0, 2*k-1, "position[%i]" % i) for i in p]
solution = [solver.IntVar(1, k, "position[%i]" % i) for i in p]
#
# declare variables
#
position = [solver.IntVar(0, 2 * k - 1, "position[%i]" % i) for i in p]
solution = [solver.IntVar(1, k, "position[%i]" % i) for i in p]
#
# constraints
#
solver.Add(solver.AllDifferent(position))
#
# constraints
#
solver.Add(solver.AllDifferent(position))
for i in range(1,k+1):
solver.Add(position[i+k-1] == position[i-1] + i+1)
solver.Add(solver.Element(solution, position[i-1]) == i)
solver.Add(solver.Element(solution, position[k+i-1]) == i)
for i in range(1, k + 1):
solver.Add(position[i + k - 1] == position[i - 1] + i + 1)
solver.Add(solver.Element(solution, position[i - 1]) == i)
solver.Add(solver.Element(solution, position[k + i - 1]) == i)
# symmetry breaking
solver.Add(solution[0] < solution[2*k-1])
# symmetry breaking
solver.Add(solution[0] < solution[2 * k - 1])
#
# search and result
#
db = solver.Phase(position,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# search and result
#
db = solver.Phase(position,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "solution:", ",".join([str(solution[i].Value()) for i in p])
num_solutions += 1
if num_sol > 0 and num_solutions >= num_sol:
break
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "solution:", ",".join([str(solution[i].Value()) for i in p])
num_solutions += 1
if num_sol > 0 and num_solutions >= num_sol:
break
solver.EndSearch()
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
k = 8
num_sol = 0
if __name__ == '__main__':
if len(sys.argv) > 1:
k = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
num_sol = string.atoi(sys.argv[2])
if __name__ == "__main__":
if len(sys.argv) > 1:
k = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
num_sol = string.atoi(sys.argv[2])
main(k, num_sol)
main(k, num_sol)

View File

@@ -34,42 +34,44 @@
* Zinc : http://hakank.org/minizinc/least_diff.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_cp_solver/
Also see my other Google CP Solver models:
http://www.hakank.org/google_cp_solver/
"""
from ortools.constraint_solver import pywrapcp
def main(unused_argv):
# Create the solver.
solver = pywrapcp.Solver('Least diff')
solver = pywrapcp.Solver("Least diff")
#
# declare variables
#
digits = range(0, 10)
a = solver.IntVar(digits, 'a')
b = solver.IntVar(digits, 'b')
c = solver.IntVar(digits, 'c')
d = solver.IntVar(digits, 'd')
e = solver.IntVar(digits, 'e')
a = solver.IntVar(digits, "a")
b = solver.IntVar(digits, "b")
c = solver.IntVar(digits, "c")
d = solver.IntVar(digits, "d")
e = solver.IntVar(digits, "e")
f = solver.IntVar(digits, 'f')
g = solver.IntVar(digits, 'g')
h = solver.IntVar(digits, 'h')
i = solver.IntVar(digits, 'i')
j = solver.IntVar(digits, 'j')
f = solver.IntVar(digits, "f")
g = solver.IntVar(digits, "g")
h = solver.IntVar(digits, "h")
i = solver.IntVar(digits, "i")
j = solver.IntVar(digits, "j")
letters = [a,b,c,d,e,f,g,h,i,j]
letters = [a, b, c, d, e, f, g, h, i, j]
x = solver.IntVar(range(0,99999), "x")
y = solver.IntVar(range(0,99999), "y")
diff = solver.IntVar(range(0,99999), "y")
x = solver.IntVar(range(0, 99999), "x")
y = solver.IntVar(range(0, 99999), "y")
diff = solver.IntVar(range(0, 99999), "y")
#
# constraints
#
solver.Add(x == 10000*a +1000*b +100*c +10*d + e)
solver.Add(y == 10000*f +1000*g +100*h +10*i + j)
solver.Add(x == 10000 * a + 1000 * b + 100 * c + 10 * d + e)
solver.Add(y == 10000 * f + 1000 * g + 100 * h + 10 * i + j)
solver.Add(diff == x - y)
solver.Add(diff > 0)
solver.Add(solver.AllDifferent(letters))
@@ -91,10 +93,10 @@ def main(unused_argv):
search_log = solver.SearchLog(100, diff)
# Note: I'm not sure what CHOOSE_PATH do, but it is fast:
# find the solution in just 4 steps
solver.Solve(solver.Phase(letters + [x,y,diff],
solver.Solve(solver.Phase(letters + [x, y, diff],
solver.CHOOSE_PATH,
solver.ASSIGN_MIN_VALUE),
[objective, search_log, collector])
[objective, search_log, collector])
# get the first (and only) solution
@@ -104,7 +106,7 @@ def main(unused_argv):
print "x:", xval
print "y:", yval
print "diff:", diffval
print xval,"-", yval,"=", diffval
print xval, "-", yval, "=", diffval
print [("abcdefghij"[i], collector.Value(0, letters[i])) for i in range(10)]
print
print "failures:", solver.Failures()
@@ -112,5 +114,5 @@ def main(unused_argv):
print "WallTime:", solver.WallTime()
print
if __name__ == '__main__':
if __name__ == "__main__":
main("cp sample")

View File

@@ -22,13 +22,15 @@
page 286f.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -41,40 +43,41 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
# data
# number of points
num = 14
# temperature
t = [20, 30, 80,125,175,225,275,325,360,420,495,540,630,700]
t = [20, 30, 80, 125, 175, 225, 275, 325, 360, 420, 495, 540, 630, 700]
# percentage gas
F = [0.0,5.8,14.7,31.6,43.2,58.3,78.4,89.4,96.4,99.1,99.5,99.9,100.0,100.0]
F = [
0.0, 5.8, 14.7, 31.6, 43.2, 58.3, 78.4, 89.4, 96.4, 99.1, 99.5, 99.9,
100.0, 100.0]
p = 4
#
# declare variables
#
a = [solver.NumVar(-100, 100, 'a[%i]' % i ) for i in range(p + 1)]
a = [solver.NumVar(-100, 100, 'a[%i]' % i) for i in range(p + 1)]
# to minimize
z = solver.Sum([(F[i] -
(sum([a[j]*t[i]**j for j in range(p+1)])))
(sum([a[j] * t[i] ** j for j in range(p + 1)])))
for i in range(num)])
#
# constraints
#
solver.Add(solver.Sum([20**i*a[i] for i in range(p+1)]) == 0)
solver.Add(solver.Sum([20 ** i * a[i] for i in range(p + 1)]) == 0)
solver.Add( (a[0] + sum([700.0**j*a[j]
for j in range(1,p+1)])) == 100.0)
solver.Add((a[0] + sum([700.0 ** j * a[j]
for j in range(1, p + 1)])) == 100.0)
for i in range(num):
solver.Add(solver.Sum([j*a[j]*t[i]**(j-1)
for j in range(p+1)]) >= 0)
solver.Add(solver.Sum([j * a[j] * t[i] ** (j - 1)
for j in range(p + 1)]) >= 0)
objective = solver.Minimize(z)

View File

@@ -41,7 +41,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -50,84 +51,83 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Lectures')
# Create the solver.
solver = pywrapcp.Solver('Lectures')
#
# data
#
#
# data
#
#
# The schedule requirements:
# lecture a cannot be held at the same time as b
# Note: 1-based
g = [
[1, 2],
[1, 4],
[3, 5],
[2, 6],
[4, 5],
[5, 6],
[1, 6]
]
#
# The schedule requirements:
# lecture a cannot be held at the same time as b
# Note: 1-based
g = [
[1, 2],
[1, 4],
[3, 5],
[2, 6],
[4, 5],
[5, 6],
[1, 6]
]
# number of nodes
n = 6
# number of nodes
n = 6
# number of edges
edges = len(g)
# number of edges
edges = len(g)
#
# declare variables
#
v = [solver.IntVar(0, n-1, 'v[%i]' % i) for i in range(n)]
#
# declare variables
#
v = [solver.IntVar(0, n - 1, 'v[%i]' % i) for i in range(n)]
# maximum color, to minimize
# Note: since Python is 0-based, the
# number of colors is +1
max_c = solver.IntVar(0, n-1, 'max_c')
# maximum color, to minimize
# Note: since Python is 0-based, the
# number of colors is +1
max_c = solver.IntVar(0, n - 1, 'max_c')
#
# constraints
#
solver.Add(max_c == solver.Max(v))
#
# constraints
#
solver.Add(max_c == solver.Max(v))
# ensure that there are no clashes
# also, adjust to 0-base
for i in range(edges):
solver.Add(v[g[i][0] - 1] != v[g[i][1] - 1])
# ensure that there are no clashes
# also, adjust to 0-base
for i in range(edges):
solver.Add(v[g[i][0]-1] != v[g[i][1]-1])
# symmetry breaking:
# - v0 has the color 0,
# - v1 has either color 0 or 1
solver.Add(v[0] == 0)
solver.Add(v[1] <= 1)
# symmetry breaking:
# - v0 has the color 0,
# - v1 has either color 0 or 1
solver.Add(v[0] == 0)
solver.Add(v[1] <= 1)
# objective
objective = solver.Minimize(max_c, 1)
# objective
objective = solver.Minimize(max_c, 1)
#
# solution and search
#
db = solver.Phase(v,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
#
# solution and search
#
db = solver.Phase(v,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db, [objective])
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'max_c:', max_c.Value() + 1, 'colors'
print 'v:', [v[i].Value() for i in range(n)]
print
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'max_c:', max_c.Value()+1, 'colors'
print 'v:', [v[i].Value() for i in range(n)]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -19,7 +19,6 @@
"""
from google.apputils import app
from ortools.graph import pywrapgraph
@@ -36,7 +35,7 @@ def RunAssignmentOn4x4Matrix():
expected_cost = cost[0][3] + cost[1][2] + cost[2][1] + cost[3][0]
assignment = pywrapgraph.LinearSumAssignment()
for source in range (0, num_sources):
for source in range(0, num_sources):
for target in range(0, num_targets):
assignment.AddArcWithCost(source, target, cost[source][target])

View File

@@ -21,7 +21,6 @@ distribute().
"""
from google.apputils import app
import gflags
from ortools.constraint_solver import pywrapcp

View File

@@ -19,88 +19,88 @@
Magic square problem.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import string, sys
import string
import sys
from ortools.constraint_solver import pywrapcp
def main(n=4):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
#
# data
#
#
# declare variables
#
x = {}
#
# declare variables
#
x = {}
for i in range(n):
for j in range(n):
x[(i, j)] = solver.IntVar(1, n * n, "x(%i,%i)" % (i, j))
x_flat = [x[(i, j)] for i in range(n) for j in range(n)]
# the sum
# s = ( n * (n*n + 1)) / 2
s = solver.IntVar(1, n * n * n, "s")
#
# constraints
#
# solver.Add(s == ( n * (n*n + 1)) / 2)
solver.Add(solver.AllDifferent(x_flat))
[solver.Add(solver.Sum([x[(i, j)] for j in range(n)]) == s) for i in range(n)]
[solver.Add(solver.Sum([x[(i, j)] for i in range(n)]) == s) for j in range(n)]
solver.Add(solver.Sum([x[(i, i)] for i in range(n)]) == s) # diag 1
solver.Add(solver.Sum([x[(i, n - i - 1)] for i in range(n)]) == s) # diag 2
# symmetry breaking
# solver.Add(x[(0,0)] == 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(s)
# db: DecisionBuilder
db = solver.Phase(x_flat,
# solver.INT_VAR_DEFAULT,
solver.CHOOSE_FIRST_UNBOUND,
# solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
# solver.ASSIGN_MIN_VALUE
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "s:", s.Value()
for i in range(n):
for j in range(n):
x[(i, j)] = solver.IntVar(1, n*n, 'x(%i,%i)' % (i, j))
x_flat = [x[(i,j)] for i in range(n) for j in range(n)]
# the sum
# s = ( n * (n*n + 1)) / 2
s = solver.IntVar(1, n*n*n,'s')
#
# constraints
#
# solver.Add(s == ( n * (n*n + 1)) / 2)
solver.Add(solver.AllDifferent(x_flat))
[solver.Add(solver.Sum([x[(i,j)] for j in range(n)]) == s) for i in range(n)]
[solver.Add(solver.Sum([x[(i,j)] for i in range(n)]) == s) for j in range(n)]
solver.Add(solver.Sum([ x[(i,i)] for i in range(n)]) == s) # diag 1
solver.Add(solver.Sum([ x[(i,n-i-1)] for i in range(n)]) == s) # diag 2
# symmetry breaking
# solver.Add(x[(0,0)] == 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(s)
# db: DecisionBuilder
db = solver.Phase(x_flat,
#solver.INT_VAR_DEFAULT,
solver.CHOOSE_FIRST_UNBOUND,
#solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_CENTER_VALUE
#solver.ASSIGN_MIN_VALUE
)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "s:", s.Value()
for i in range(n):
for j in range(n):
print "%2i" % x[(i,j)].Value(),
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
print "%2i" % x[(i, j)].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
n = 4
if __name__ == '__main__':
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)

View File

@@ -25,90 +25,89 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import string, sys
import string
import sys
from ortools.constraint_solver import pywrapcp
def main(n=3):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
# n = 3
#
# data
#
# n = 3
#
# declare variables
#
x = {}
#
# declare variables
#
x = {}
for i in range(n):
for j in range(n):
x[(i, j)] = solver.IntVar(1, 13, "x(%i,%i)" % (i, j))
x_flat = [x[(i, j)] for i in range(n) for j in range(n)]
s = solver.IntVar(1, 13 * 4, "s")
counts = [solver.IntVar(0, 4, "counts(%i)" % i) for i in range(14)]
#
# constraints
#
solver.Add(solver.Distribute(x_flat, range(14), counts))
# the standard magic square constraints (sans all_different)
[solver.Add(solver.Sum([x[(i, j)] for j in range(n)]) == s) for i in range(n)]
[solver.Add(solver.Sum([x[(i, j)] for i in range(n)]) == s) for j in range(n)]
solver.Add(solver.Sum([x[(i, i)] for i in range(n)]) == s) # diag 1
solver.Add(solver.Sum([x[(i, n - i - 1)] for i in range(n)]) == s) # diag 2
# redundant constraint
solver.Add(solver.Sum(counts) == n * n)
# objective
objective = solver.Maximize(s, 1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(s)
solution.Add(counts)
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
print "s:", s.Value()
print "counts:", [counts[i].Value() for i in range(14)]
for i in range(n):
for j in range(n):
x[(i, j)] = solver.IntVar(1, 13, 'x(%i,%i)' % (i, j))
x_flat = [x[(i,j)] for i in range(n) for j in range(n)]
s = solver.IntVar(1, 13*4,'s')
counts = [solver.IntVar(0,4,"counts(%i)"%i) for i in range(14)]
#
# constraints
#
solver.Add(solver.Distribute(x_flat, range(14), counts))
# the standard magic square constraints (sans all_different)
[solver.Add(solver.Sum([x[(i,j)] for j in range(n)]) == s) for i in range(n)]
[solver.Add(solver.Sum([x[(i,j)] for i in range(n)]) == s) for j in range(n)]
solver.Add(solver.Sum([ x[(i,i)] for i in range(n)]) == s ) # diag 1
solver.Add(solver.Sum([ x[(i,n-i-1)] for i in range(n)]) == s) # diag 2
# redundant constraint
solver.Add(solver.Sum(counts) == n*n)
# objective
objective = solver.Maximize(s,1)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x_flat)
solution.Add(s)
solution.Add(counts)
# db: DecisionBuilder
db = solver.Phase(x_flat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db,[objective])
num_solutions = 0
while solver.NextSolution():
print "s:", s.Value()
print "counts:", [counts[i].Value() for i in range(14)]
for i in range(n):
for j in range(n):
print x[(i,j)].Value(),
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
print x[(i, j)].Value(),
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
n = 3
if __name__ == '__main__':
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)

View File

@@ -39,7 +39,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
@@ -49,7 +50,9 @@ from ortools.linear_solver import pywraplp
# n: size of matrix
# use_output_matrix: use the output_matrix
#
def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
def main(n=3, sol='GLPK', use_output_matrix=0):
# Create the solver.
@@ -60,21 +63,19 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
solver = pywraplp.Solver('CoinsGridGLPK',
pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING)
else:
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
# Using CLP
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
#
# data
#
print 'n = ', n
# range_n = range(1, n+1)
range_n = range(0, n)
N = n*n
N = n * n
range_N = range(1, N + 1)
#
@@ -86,15 +87,15 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
for i in range_n:
for j in range_n:
for k in range_N:
x[i,j,k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))
x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))
## For output. Much slower....
# For output. Much slower....
if use_output_matrix == 1:
print 'Using an output matrix'
square = {}
for i in range_n:
for j in range_n:
square[i,j] = solver.IntVar(1, n*n, 'square[%i,%i]' % (i, j))
square[i, j] = solver.IntVar(1, n * n, 'square[%i,%i]' % (i, j))
# the magic sum
s = solver.IntVar(1, n * n * n, 's')
@@ -106,41 +107,40 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
# each cell must be assigned exactly one integer
for i in range_n:
for j in range_n:
solver.Add(solver.Sum([x[i,j,k] for k in range_N]) == 1)
solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1)
# each integer must be assigned exactly to one cell
for k in range_N:
solver.Add(solver.Sum([x[i,j,k]
solver.Add(solver.Sum([x[i, j, k]
for i in range_n
for j in range_n]) == 1)
# # the sum in each row must be the magic sum
for i in range_n:
solver.Add(solver.Sum([k * x[i,j,k]
for j in range_n
for k in range_N]) == s)
solver.Add(solver.Sum([k * x[i, j, k]
for j in range_n
for k in range_N]) == s)
# # the sum in each column must be the magic sum
for j in range_n:
solver.Add(solver.Sum([k * x[i,j,k]
for i in range_n
for k in range_N]) == s)
solver.Add(solver.Sum([k * x[i, j, k]
for i in range_n
for k in range_N]) == s)
# # the sum in the diagonal must be the magic sum
solver.Add(solver.Sum([k * x[i,i,k]
solver.Add(solver.Sum([k * x[i, i, k]
for i in range_n
for k in range_N]) == s)
# # the sum in the co-diagonal must be the magic sum
if range_n[0] == 1:
# for range_n = 1..n
solver.Add(solver.Sum([k * x[i,n-i+1,k]
for i in range_n
for k in range_N]) == s)
# for range_n = 1..n
solver.Add(solver.Sum([k * x[i, n - i + 1, k]
for i in range_n
for k in range_N]) == s)
else:
# for range_n = 0..n-1
solver.Add(solver.Sum([k * x[i,n-i-1,k]
solver.Add(solver.Sum([k * x[i, n - i - 1, k]
for i in range_n
for k in range_N]) == s)
@@ -148,9 +148,8 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
if use_output_matrix == 1:
for i in range_n:
for j in range_n:
solver.Add(square[i,j] ==
solver.Sum([k * x[i,j,k] for k in range_N]))
solver.Add(square[i, j] ==
solver.Sum([k * x[i, j, k] for k in range_N]))
#
# solution and search
@@ -169,14 +168,14 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
else:
for i in range_n:
for j in range_n:
print sum([int(k * x[i,j,k].SolutionValue()) for k in range_N]), " ",
print sum([int(k * x[i, j, k].SolutionValue()) for k in range_N]), ' ',
print
print "\nx:"
print '\nx:'
for i in range_n:
for j in range_n:
for k in range_N:
print int(x[i,j,k].SolutionValue()),
print int(x[i, j, k].SolutionValue()),
print
print
@@ -186,19 +185,19 @@ def main(n = 3, sol = 'GLPK', use_output_matrix = 0):
if __name__ == '__main__':
n = 3
sol = 'GLPK'
use_output_matrix = 0
if len(sys.argv) > 1:
n = int(sys.argv[1])
n = 3
sol = 'GLPK'
use_output_matrix = 0
if len(sys.argv) > 1:
n = int(sys.argv[1])
if len(sys.argv) > 2:
sol = sys.argv[2]
if sol != 'GLPK' and sol != 'CBC':
print 'Solver must be either GLPK or CBC'
sys.exit(1)
if len(sys.argv) > 2:
sol = sys.argv[2]
if sol != 'GLPK' and sol != 'CBC':
print 'Solver must be either GLPK or CBC'
sys.exit(1)
if len(sys.argv) > 3:
use_output_matrix = int(sys.argv[3])
if len(sys.argv) > 3:
use_output_matrix = int(sys.argv[3])
main(n, sol, use_output_matrix)
main(n, sol, use_output_matrix)

View File

@@ -30,79 +30,77 @@
* Zinc: http://hakank.org/minizinc/map.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Map coloring')
# Create the solver.
solver = pywrapcp.Solver("Map coloring")
#
# data
#
Belgium = 0
Denmark = 1
France = 2
Germany = 3
Netherlands = 4
Luxembourg = 5
#
# data
#
Belgium = 0
Denmark = 1
France = 2
Germany = 3
Netherlands = 4
Luxembourg = 5
n = 6
max_num_colors = 4
n = 6
max_num_colors = 4
# declare variables
color = [solver.IntVar(1,max_num_colors, 'x%i' % i) for i in range(n)]
# declare variables
color = [solver.IntVar(1, max_num_colors, "x%i" % i) for i in range(n)]
#
# constraints
#
solver.Add(color[Belgium] == 1) # Symmetry breaking
solver.Add(color[France] != color[Belgium])
solver.Add(color[France] != color[Luxembourg])
solver.Add(color[France] != color[Germany])
solver.Add(color[Luxembourg] != color[Germany])
solver.Add(color[Luxembourg] != color[Belgium])
solver.Add(color[Belgium] != color[Netherlands])
solver.Add(color[Belgium] != color[Germany])
solver.Add(color[Germany] != color[Netherlands])
solver.Add(color[Germany] != color[Denmark])
#
# constraints
#
solver.Add(color[Belgium] == 1) # Symmetry breaking
solver.Add(color[France] != color[Belgium])
solver.Add(color[France] != color[Luxembourg])
solver.Add(color[France] != color[Germany])
solver.Add(color[Luxembourg] != color[Germany])
solver.Add(color[Luxembourg] != color[Belgium])
solver.Add(color[Belgium] != color[Netherlands])
solver.Add(color[Belgium] != color[Germany])
solver.Add(color[Germany] != color[Netherlands])
solver.Add(color[Germany] != color[Denmark])
#
# solution and search
#
solution = solver.Assignment()
solution.Add([color[i] for i in range(n)])
collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# search_log = solver.SearchLog(100, x[0])
solver.Solve(solver.Phase([color[i] for i in range(n)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
colorval = [collector.Value(s, color[i]) for i in range(n)]
print "color:", colorval
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
else:
print "No solutions found"
#
# solution and search
#
solution = solver.Assignment()
solution.Add([color[i] for i in range(n)])
collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# search_log = solver.SearchLog(100, x[0])
solver.Solve(solver.Phase([color[i] for i in range(n)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
colorval = [collector.Value(s, color[i]) for i in range(n)]
print "color:", colorval
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
else:
print "No solutions found"
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -44,7 +44,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -53,86 +54,82 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Marathon')
# Create the solver.
solver = pywrapcp.Solver('Marathon')
#
# data
#
n = 6
#
# data
#
n = 6
runners_str = ['Dominique', 'Ignace', 'Naren',
'Olivier', 'Philippe', 'Pascal']
runners_str = ['Dominique', 'Ignace', 'Naren',
'Olivier', 'Philippe', 'Pascal']
#
# declare variables
#
runners = [solver.IntVar(1, n, 'runners[%i]' % i) for i in range(n)]
Dominique, Ignace, Naren, Olivier, Philippe, Pascal = runners
#
# declare variables
#
runners = [solver.IntVar(1, n, 'runners[%i]' % i) for i in range(n)]
Dominique, Ignace, Naren, Olivier, Philippe, Pascal = runners
#
# constraints
#
solver.Add(solver.AllDifferent(runners))
# a: Olivier not last
solver.Add(Olivier != n)
# b: Dominique, Pascal and Ignace before Naren and Olivier
solver.Add(Dominique < Naren)
solver.Add(Dominique < Olivier)
solver.Add(Pascal < Naren)
solver.Add(Pascal < Olivier)
solver.Add(Ignace < Naren)
solver.Add(Ignace < Olivier)
#
# constraints
#
solver.Add(solver.AllDifferent(runners))
# c: Dominique better than third
solver.Add(Dominique < 3)
# a: Olivier not last
solver.Add(Olivier != n)
# d: Philippe is among the first four
solver.Add(Philippe <= 4)
# b: Dominique, Pascal and Ignace before Naren and Olivier
solver.Add(Dominique < Naren)
solver.Add(Dominique < Olivier)
solver.Add(Pascal < Naren)
solver.Add(Pascal < Olivier)
solver.Add(Ignace < Naren)
solver.Add(Ignace < Olivier)
# e: Ignace neither second nor third
solver.Add(Ignace != 2)
solver.Add(Ignace != 3)
# c: Dominique better than third
solver.Add(Dominique < 3)
# f: Pascal three places earlier than Naren
solver.Add(Pascal + 3 == Naren)
# d: Philippe is among the first four
solver.Add(Philippe <= 4)
# g: Neither Ignace nor Dominique on fourth position
solver.Add(Ignace != 4)
solver.Add(Dominique != 4)
# e: Ignace neither second nor third
solver.Add(Ignace != 2)
solver.Add(Ignace != 3)
#
# solution and search
#
db = solver.Phase(runners,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
# f: Pascal three places earlier than Naren
solver.Add(Pascal + 3 == Naren)
solver.NewSearch(db)
# g: Neither Ignace nor Dominique on fourth position
solver.Add(Ignace != 4)
solver.Add(Dominique != 4)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
runners_val = [runners[i].Value() for i in range(n)]
print 'runners:', runners_val
print 'Places:'
for i in range(1, n + 1):
for j in range(n):
if runners_val[j] == i:
print '%i: %s' % (i, runners_str[j])
print
#
# solution and search
#
db = solver.Phase(runners,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
runners_val = [runners[i].Value() for i in range(n)]
print 'runners:', runners_val
print "Places:"
for i in range(1, n+1):
for j in range(n):
if runners_val[j] == i:
print "%i: %s" % (i, runners_str[j])
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -25,108 +25,105 @@
* MiniZinc: http://www.hakank.org/minizinc/max_flow_taha.mzn
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Max flow problem, Taha')
# Create the solver.
solver = pywrapcp.Solver('Max flow problem, Taha')
#
# data
#
n = 5
start = 0
end = n-1
#
# data
#
n = 5
start = 0
end = n - 1
nodes = range(n)
nodes = range(n)
# cost matrix
c = [
[0, 20, 30, 10, 0],
[0, 0, 40, 0, 30],
[0, 0, 0, 10, 20],
[0, 0, 5, 0, 20],
[0, 0, 0, 0, 0]
]
# cost matrix
c = [
[0, 20, 30, 10, 0],
[0, 0, 40, 0, 30],
[0, 0, 0, 10, 20],
[0, 0, 5, 0, 20],
[0, 0, 0, 0, 0]
]
#
# declare variables
#
x = {}
for i in nodes:
for j in nodes:
x[i, j] = solver.IntVar(0, c[i][j], 'x[%i,%i]' % (i, j))
x_flat = [x[i, j] for i in nodes for j in nodes]
out_flow = [solver.IntVar(0, 10000, 'out_flow[%i]' % i) for i in nodes]
in_flow = [solver.IntVar(0, 10000, 'in_flow[%i]' % i) for i in nodes]
#
# declare variables
#
x = {}
total = solver.IntVar(0, 10000, 'z')
#
# constraints
#
cost_sum = solver.Sum([x[start, j] for j in nodes if c[start][j] > 0])
solver.Add(total == cost_sum)
for i in nodes:
in_flow_sum = solver.Sum([x[j, i] for j in nodes if c[j][i] > 0])
solver.Add(in_flow[i] == in_flow_sum)
out_flow_sum = solver.Sum([x[i, j] for j in nodes if c[i][j] > 0])
solver.Add(out_flow[i] == out_flow_sum)
# in_flow == out_flow
for i in nodes:
if i != start and i != end:
solver.Add(out_flow[i] - in_flow[i] == 0)
s1 = [x[i, start] for i in nodes if c[i][start] > 0]
if len(s1) > 0:
solver.Add(solver.Sum([x[i, start]
for i in nodes if c[i][start] > 0] == 0))
s2 = [x[end, j] for j in nodes if c[end][j] > 0]
if len(s2) > 0:
solver.Add(solver.Sum([x[end, j]
for j in nodes if c[end][j] > 0]) == 0)
# objective: maximize total cost
objective = solver.Maximize(total, 1)
#
# solution and search
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total:', total.Value()
print 'in_flow:', [in_flow[i].Value() for i in nodes]
print 'out_flow:', [out_flow[i].Value() for i in nodes]
for i in nodes:
for j in nodes:
x[i,j] = solver.IntVar(0, c[i][j], 'x[%i,%i]' % (i, j))
for j in nodes:
print '%2i' % x[i, j].Value(),
print
print
x_flat = [x[i,j] for i in nodes for j in nodes]
out_flow = [solver.IntVar(0, 10000, 'out_flow[%i]' % i) for i in nodes]
in_flow = [solver.IntVar(0, 10000, 'in_flow[%i]' % i) for i in nodes]
total = solver.IntVar(0, 10000, 'z')
#
# constraints
#
cost_sum = solver.Sum([x[start,j] for j in nodes if c[start][j] > 0])
solver.Add(total == cost_sum)
for i in nodes:
in_flow_sum = solver.Sum([x[j,i] for j in nodes if c[j][i] > 0])
solver.Add(in_flow[i] == in_flow_sum)
out_flow_sum = solver.Sum([x[i,j] for j in nodes if c[i][j] > 0])
solver.Add(out_flow[i] == out_flow_sum)
# in_flow == out_flow
for i in nodes:
if i != start and i != end:
solver.Add(out_flow[i] - in_flow[i]==0)
s1 = [x[i,start] for i in nodes if c[i][start] > 0]
if len(s1) > 0:
solver.Add(solver.Sum([x[i,start]
for i in nodes if c[i][start] > 0] == 0))
s2 = [x[end,j] for j in nodes if c[end][j] > 0]
if len(s2) > 0:
solver.Add(solver.Sum([x[end,j]
for j in nodes if c[end][j] > 0]) == 0)
# objective: maximize total cost
objective = solver.Maximize(total, 1)
#
# solution and search
#
db = solver.Phase(x_flat,
solver.INT_VAR_DEFAULT,
solver.ASSIGN_MAX_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total:', total.Value()
print 'in_flow:', [in_flow[i].Value() for i in nodes]
print 'out_flow:', [out_flow[i].Value() for i in nodes]
for i in nodes:
for j in nodes:
print '%2i' % x[i,j].Value(),
print
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -25,7 +25,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
@@ -33,116 +34,112 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Max flow problem, Winston')
# Create the solver.
solver = pywrapcp.Solver('Max flow problem, Winston')
#
# data
#
n = 5
nodes = range(n)
#
# data
#
n = 5
nodes = range(n)
# the arcs
# Note:
# This is 1-based to be compatible with other
# implementations.
arcs1 = [
[1, 2],
[1, 3],
[2, 3],
[2, 4],
[3, 5],
[4, 5],
[5, 1]
]
# the arcs
# Note:
# This is 1-based to be compatible with other
# implementations.
arcs1 = [
[1, 2],
[1, 3],
[2, 3],
[2, 4],
[3, 5],
[4, 5],
[5, 1]
]
# convert arcs to 0-based
arcs = []
for (a_from, a_to) in arcs1:
a_from -= 1
a_to -= 1
arcs.append([a_from, a_to])
# convert arcs to 0-based
arcs = []
for (a_from, a_to) in arcs1:
a_from -= 1
a_to -= 1
arcs.append([a_from, a_to])
num_arcs = len(arcs)
num_arcs = len(arcs)
# capacities
cap = [2,3,3,4,2,1,100]
# capacities
cap = [2, 3, 3, 4, 2, 1, 100]
# convert arcs to matrix
# for sanity checking below
mat = {}
# convert arcs to matrix
# for sanity checking below
mat = {}
for i in nodes:
for j in nodes:
c = 0
for k in range(num_arcs):
if arcs[k][0] == i and arcs[k][1] == j:
c = 1
mat[i, j] = c
#
# declare variables
#
flow = {}
for i in nodes:
for j in nodes:
flow[i, j] = solver.IntVar(0, 200, 'flow %i %i' % (i, j))
flow_flat = [flow[i, j] for i in nodes for j in nodes]
z = solver.IntVar(0, 10000, 'z')
#
# constraints
#
solver.Add(z == flow[n - 1, 0])
# capacity of arcs
for i in range(num_arcs):
solver.Add(flow[arcs[i][0], arcs[i][1]] <= cap[i])
# inflows == outflows
for i in nodes:
s1 = solver.Sum([flow[arcs[k][0], arcs[k][1]]
for k in range(num_arcs) if arcs[k][1] == i])
s2 = solver.Sum([flow[arcs[k][0], arcs[k][1]]
for k in range(num_arcs) if arcs[k][0] == i])
solver.Add(s1 == s2)
# sanity: just arcs with connections can have a flow
for i in nodes:
for j in nodes:
if mat[i, j] == 0:
solver.Add(flow[i, j] == 0)
# objective: maximize z
objective = solver.Maximize(z, 1)
#
# solution and search
#
db = solver.Phase(flow_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'z:', z.Value()
for i in nodes:
for j in nodes:
c = 0;
for k in range(num_arcs):
if arcs[k][0] == i and arcs[k][1] == j:
c = 1
mat[i,j] = c
for j in nodes:
print flow[i, j].Value(),
print
print
#
# declare variables
#
flow = {}
for i in nodes:
for j in nodes:
flow[i,j] = solver.IntVar(0, 200, 'flow %i %i' % (i, j))
flow_flat = [flow[i,j] for i in nodes for j in nodes]
z = solver.IntVar(0, 10000, 'z')
#
# constraints
#
solver.Add(z == flow[n-1, 0])
# capacity of arcs
for i in range(num_arcs):
solver.Add(flow[arcs[i][0], arcs[i][1]] <= cap[i])
# inflows == outflows
for i in nodes:
s1 = solver.Sum([flow[arcs[k][0], arcs[k][1]]
for k in range(num_arcs) if arcs[k][1] == i])
s2 = solver.Sum([flow[arcs[k][0], arcs[k][1]]
for k in range(num_arcs) if arcs[k][0] == i])
solver.Add(s1 == s2)
# sanity: just arcs with connections can have a flow
for i in nodes:
for j in nodes:
if mat[i,j] == 0:
solver.Add(flow[i,j] == 0)
# objective: maximize z
objective = solver.Maximize(z, 1)
#
# solution and search
#
db = solver.Phase(flow_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "z:", z.Value()
for i in nodes:
for j in nodes:
print flow[i,j].Value(),
print
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -60,7 +60,8 @@
* Zinc: http://www.hakank.org/minizinc/minesweeper.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
@@ -69,173 +70,170 @@ default_r = 8
default_c = 8
X = -1
default_game = [
[2,3,X,2,2,X,2,1],
[X,X,4,X,X,4,X,2],
[X,X,X,X,X,X,4,X],
[X,5,X,6,X,X,X,2],
[2,X,X,X,5,5,X,2],
[1,3,4,X,X,X,4,X],
[0,1,X,4,X,X,X,3],
[0,1,2,X,2,3,X,2]
]
[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]
]
def main(game="", r="", c=""):
# Create the solver.
solver = pywrapcp.Solver('Minesweeper')
# Create the solver.
solver = pywrapcp.Solver("Minesweeper")
#
# data
#
#
# data
#
# Set default problem
if game == "":
game = default_game
r = default_r
c = default_c
else:
print "rows:", r, " cols:", c
# Set default problem
if game == "":
game = default_game
r = default_r
c = default_c
else:
print "rows:", r, " cols:", c
#
# Default problem from "Some Minesweeper Configurations",page 3
# (same as problem instance minesweeper_config3.txt)
# It has 4 solutions
#
# r = 8
# c = 8
# X = -1
# game = [
# [2,3,X,2,2,X,2,1],
# [X,X,4,X,X,4,X,2],
# [X,X,X,X,X,X,4,X],
# [X,5,X,6,X,X,X,2],
# [2,X,X,X,5,5,X,2],
# [1,3,4,X,X,X,4,X],
# [0,1,X,4,X,X,X,3],
# [0,1,2,X,2,3,X,2]
# ]
#
# Default problem from "Some Minesweeper Configurations",page 3
# (same as problem instance minesweeper_config3.txt)
# It has 4 solutions
#
# r = 8
# c = 8
# X = -1
# game = [
# [2,3,X,2,2,X,2,1],
# [X,X,4,X,X,4,X,2],
# [X,X,X,X,X,X,4,X],
# [X,5,X,6,X,X,X,2],
# [2,X,X,X,5,5,X,2],
# [1,3,4,X,X,X,4,X],
# [0,1,X,4,X,X,X,3],
# [0,1,2,X,2,3,X,2]
# ]
S = [-1, 0, 1] # for the neighbors of "this" cell
S = [-1,0,1] # for the neighbors of "this" cell
# print problem instance
print "Problem:"
for i in range(r):
for j in range(c):
if game[i][j] == X:
print "X",
else:
print game[i][j],
print
# print problem instance
print "Problem:"
for i in range(r):
for j in range(c):
if game[i][j] == X:
print "X",
else:
print game[i][j],
print
print
# declare variables
mines = {}
for i in range(r):
for j in range(c):
mines[(i, j)] = solver.IntVar(0, 1, "mines %i %i" % (i, j))
# declare variables
mines = {}
for i in range(r):
#
# constraints
#
for i in range(r):
for j in range(c):
if game[i][j] >= 0:
solver.Add(mines[i, j] == 0)
# this cell is the sum of all the surrounding cells
solver.Add(
game[i][j] == solver.Sum([mines[i + a, j + b]
for a in S for b in S
if i + a >= 0 and
j + b >= 0 and
i + a < r and
j + b < c])
)
if game[i][j] > X:
# This cell cannot be a mine
solver.Add(mines[i, j] == 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([mines[(i, j)] for i in range(r) for j in range(c)])
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase([mines[(i, j)] for i in range(r) for j in range(c)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
minesval = [collector.Value(s, mines[(i, j)])
for i in range(r) for j in range(c)]
for i in range(r):
for j in range(c):
mines[(i,j)] = solver.IntVar(0,1, 'mines %i %i' % (i, j))
#
# constraints
#
for i in range(r):
for j in range(c):
if game[i][j] >= 0:
solver.Add(mines[i,j] == 0)
# this cell is the sum of all the surrounding cells
solver.Add(
game[i][j] == solver.Sum([mines[i+a,j+b]
for a in S for b in S
if i + a >=0 and
j + b >=0 and
i + a < r and
j + b < c
])
)
if game[i][j] > X:
# This cell cannot be a mine
solver.Add(mines[i,j] == 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([mines[(i,j)] for i in range(r) for j in range(c)])
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase([mines[(i,j)] for i in range(r) for j in range(c)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
minesval = [collector.Value(s, mines[(i,j)])
for i in range(r) for j in range(c)]
for i in range(r):
for j in range(c):
print minesval[i*c+j],
print
print
print minesval[i * c + j],
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
else:
print "No solutions found"
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
else:
print "No solutions found"
#
# Read a problem instance from a file
#
def read_problem(file):
f = open(file, 'r')
rows = int(f.readline())
cols = int(f.readline())
game = []
for i in range(rows):
x = f.readline()
row = [0]*cols
for j in range(cols):
if x[j] == ".":
tmp = -1
else:
tmp = int(x[j])
row[j] = tmp
game.append(row)
return [game, rows, cols]
f = open(file, "r")
rows = int(f.readline())
cols = int(f.readline())
game = []
for i in range(rows):
x = f.readline()
row = [0] * cols
for j in range(cols):
if x[j] == ".":
tmp = -1
else:
tmp = int(x[j])
row[j] = tmp
game.append(row)
return [game, rows, cols]
#
# Print the mines
#
def print_mines(mines, rows, cols):
for i in range(rows):
for j in range(cols):
print mines[i,j],
print ''
for i in range(rows):
for j in range(cols):
print mines[i, j],
print ""
def print_game(game, rows, cols):
for i in range(rows):
for j in range(cols):
print game[i][j],
print ''
for i in range(rows):
for j in range(cols):
print game[i][j],
print ""
if __name__ == '__main__':
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[game, rows, cols] = read_problem(file)
# print_game(game, rows, cols)
main(game, rows, cols)
else:
main()
if __name__ == "__main__":
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[game, rows, cols] = read_problem(file)
# print_game(game, rows, cols)
main(game, rows, cols)
else:
main()

View File

@@ -44,7 +44,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -53,73 +54,70 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Mr Smith problem')
# Create the solver.
solver = pywrapcp.Solver('Mr Smith problem')
#
# data
#
n = 5
#
# data
#
n = 5
#
# declare variables
#
x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(n)]
Mr_Smith, Mrs_Smith, Matt, John, Tim = x
#
# declare variables
#
x = [solver.IntVar(0, 1, 'x[%i]' % i) for i in range(n)]
Mr_Smith, Mrs_Smith, Matt, John, Tim = x
#
# constraints
#
#
# I've kept the MiniZinc constraints for clarity
# and debugging.
#
#
# constraints
#
# If Mr Smith comes then his wife will come too.
# (Mr_Smith -> Mrs_Smith)
solver.Add(Mr_Smith - Mrs_Smith <= 0)
#
# I've kept the MiniZinc constraints for clarity
# and debugging.
#
# At least one of their two sons Matt and John will come.
# (Matt \/ John)
solver.Add(Matt + John >= 1)
# If Mr Smith comes then his wife will come too.
# (Mr_Smith -> Mrs_Smith)
solver.Add(Mr_Smith-Mrs_Smith <= 0)
# Either Mrs Smith or Tim will come but not both.
# bool2int(Mrs_Smith) + bool2int(Tim) = 1 /\
# (Mrs_Smith xor Tim)
solver.Add(Mrs_Smith + Tim == 1)
# At least one of their two sons Matt and John will come.
# (Matt \/ John)
solver.Add(Matt+John >= 1)
# Either Tim and John will come or neither will come.
# (Tim = John)
solver.Add(Tim == John)
# Either Mrs Smith or Tim will come but not both.
# bool2int(Mrs_Smith) + bool2int(Tim) = 1 /\
# (Mrs_Smith xor Tim)
solver.Add(Mrs_Smith + Tim == 1)
# If Matt comes /\ then John and his father will also come.
# (Matt -> (John /\ Mr_Smith))
solver.Add(Matt - (John * Mr_Smith) <= 0)
# Either Tim and John will come or neither will come.
# (Tim = John)
solver.Add(Tim == John)
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
# If Matt comes /\ then John and his father will also come.
# (Matt -> (John /\ Mr_Smith))
solver.Add(Matt - (John*Mr_Smith) <= 0)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -64,7 +64,7 @@ def make_transition_tuples(pattern):
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0];
tmp = [0]
c = 0
for pattern_index in range(p_len):
tmp.extend([1] * pattern[pattern_index])
@@ -101,6 +101,7 @@ def check_rule(rules, y):
initial_state,
accepting_states))
def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
# Create the solver.
@@ -139,7 +140,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
for j in range(cols):
check_rule(col_rules[j], [board[i, j] for i in range(rows)])
#
# solution and search
#
@@ -189,34 +189,34 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
rows = 12
row_rule_len = 3
row_rules = [
[0,0,2],
[0,1,2],
[0,1,1],
[0,0,2],
[0,0,1],
[0,0,3],
[0,0,3],
[0,2,2],
[0,2,1],
[2,2,1],
[0,2,3],
[0,2,2]
]
[0, 0, 2],
[0, 1, 2],
[0, 1, 1],
[0, 0, 2],
[0, 0, 1],
[0, 0, 3],
[0, 0, 3],
[0, 2, 2],
[0, 2, 1],
[2, 2, 1],
[0, 2, 3],
[0, 2, 2]
]
cols = 10
col_rule_len = 2
col_rules = [
[2,1],
[1,3],
[2,4],
[3,4],
[0,4],
[0,3],
[0,3],
[0,3],
[0,2],
[0,2]
]
[2, 1],
[1, 3],
[2, 4],
[3, 4],
[0, 4],
[0, 3],
[0, 3],
[0, 3],
[0, 2],
[0, 2]
]
if __name__ == '__main__':

View File

@@ -49,7 +49,8 @@
to about 1 second'
http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html
* 'Comet: regular constraint, a much faster Nonogram with the regular constraint,
* 'Comet: regular constraint, a much faster Nonogram with the regular
constraint,
some OPL models, and more'
http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html
@@ -61,7 +62,8 @@
Note: nonogram_create_automaton2.mzn is the preferred model
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -92,48 +94,49 @@ from ortools.constraint_solver import pywrapcp
# F : accepting states
def regular(x, Q, S, d, q0, F):
solver = x[0].solver()
solver = x[0].solver()
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# int d2[0..Q, 1..S]
d2 = []
for i in range(Q+1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i-1][j])
d2.append(row)
# int d2[0..Q, 1..S]
d2 = []
for i in range(Q + 1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i - 1][j])
d2.append(row)
d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)]
d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
m = 0
n = len(x)
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)]
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1)))
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(
a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))
#
@@ -142,168 +145,165 @@ def regular(x, Q, S, d, q0, F):
#
def make_transition_matrix(pattern):
p_len = len(pattern)
num_states = p_len + sum(pattern)
p_len = len(pattern)
num_states = p_len + sum(pattern)
# this is for handling 0-clues. It generates
# just the state 1,2
if num_states == 0:
num_states = 1
# this is for handling 0-clues. It generates
# just the state 1,2
if num_states == 0:
num_states = 1
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states-1:
c += 1
tmp[c] = 0
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states - 1:
c += 1
tmp[c] = 0
t_matrix[num_states-1][0] = num_states
t_matrix[num_states-1][1] = 0
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i+1
t_matrix[i][1] = i+2
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
else:
if i < num_states - 1:
if tmp[i + 1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i + 2
else:
if i < num_states-1:
if tmp[i+1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i+2
else:
t_matrix[i][0] = i+2
t_matrix[i][1] = 0
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
# print 'The states:'
# for i in range(num_states):
# for j in range(2):
# print t_matrix[i][j],
# print
# print
# print 'The states:'
# for i in range(num_states):
# for j in range(2):
# print t_matrix[i][j],
# print
# print
return t_matrix
return t_matrix
#
# check each rule by creating an automaton
# and regular
#
def check_rule(rules, y):
solver = y[0].solver()
solver = y[0].solver()
r_len = sum([1 for i in range(len(rules)) if rules[i] > 0])
rules_tmp = []
for i in range(len(rules)):
if rules[i] > 0:
rules_tmp.append(rules[i])
r_len = sum([1 for i in range(len(rules)) if rules[i] > 0])
rules_tmp = []
for i in range(len(rules)):
if rules[i] > 0:
rules_tmp.append(rules[i])
transition_fn = make_transition_matrix(rules_tmp)
n_states = len(transition_fn)
input_max = 2
transition_fn = make_transition_matrix(rules_tmp)
n_states = len(transition_fn)
input_max = 2
# Note: we cannot use 0 since it's the failing state
initial_state = 1
accepting_states = [n_states] # This is the last state
regular(y, n_states, input_max, transition_fn,
initial_state, accepting_states)
# Note: we cannot use 0 since it's the failing state
initial_state = 1
accepting_states = [n_states] # This is the last state
regular(y, n_states, input_max, transition_fn,
initial_state, accepting_states)
def main(rows, row_rule_len, row_rules,
cols, col_rule_len, col_rules):
# Create the solver.
solver = pywrapcp.Solver('Regular test')
# Create the solver.
solver = pywrapcp.Solver('Regular test')
#
# data
#
#
# variables
#
board = {}
for i in range(rows):
for j in range(cols):
board[i,j] = solver.IntVar(1,2,'board[%i,%i]' % (i,j))
board_flat = [board[i,j] for i in range(rows) for j in range(cols)]
# Flattened board for labeling.
# This labeling was inspired by a suggestion from
# Pascal Van Hentenryck about my Comet nonogram model.
board_label = []
if rows * row_rule_len < cols * col_rule_len:
for i in range(rows):
for j in range(cols):
board_label.append(board[i,j])
else:
for j in range(cols):
for i in range(rows):
board_label.append(board[i,j])
#
# constraints
#
for i in range(rows):
check_rule([row_rules[i][j] for j in range(row_rule_len)],
[board[i,j] for j in range(cols)])
#
# data
#
#
# variables
#
board = {}
for i in range(rows):
for j in range(cols):
check_rule([col_rules[j][k] for k in range(col_rule_len)],
[board[i,j] for i in range(rows)])
board[i, j] = solver.IntVar(1, 2, 'board[%i,%i]' % (i, j))
board_flat = [board[i, j] for i in range(rows) for j in range(cols)]
# Flattened board for labeling.
# This labeling was inspired by a suggestion from
# Pascal Van Hentenryck about my Comet nonogram model.
board_label = []
if rows * row_rule_len < cols * col_rule_len:
for i in range(rows):
for j in range(cols):
board_label.append(board[i, j])
else:
for j in range(cols):
for i in range(rows):
board_label.append(board[i, j])
#
# solution and search
#
db = solver.Phase(board_label,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
#
# constraints
#
for i in range(rows):
check_rule([row_rules[i][j] for j in range(row_rule_len)],
[board[i, j] for j in range(cols)])
solver.NewSearch(db)
for j in range(cols):
check_rule([col_rules[j][k] for k in range(col_rule_len)],
[board[i, j] for i in range(rows)])
num_solutions = 0
while solver.NextSolution():
print
num_solutions += 1
for i in range(rows):
row = [board[i,j].Value()-1 for j in range(cols)]
row_pres = []
for j in row:
if j == 1:
row_pres.append('#')
else:
row_pres.append(' ')
print ' ', ''.join(row_pres)
#
# solution and search
#
db = solver.Phase(board_label,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
print
print ' ', '-' * cols
solver.NewSearch(db)
if num_solutions >= 2:
print '2 solutions is enough...'
break
solver.EndSearch()
num_solutions = 0
while solver.NextSolution():
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
num_solutions += 1
for i in range(rows):
row = [board[i, j].Value() - 1 for j in range(cols)]
row_pres = []
for j in row:
if j == 1:
row_pres.append('#')
else:
row_pres.append(' ')
print ' ', ''.join(row_pres)
print
print ' ', '-' * cols
if num_solutions >= 2:
print '2 solutions is enough...'
break
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
#
@@ -315,39 +315,39 @@ def main(rows, row_rule_len, row_rules,
rows = 12
row_rule_len = 3
row_rules = [
[0,0,2],
[0,1,2],
[0,1,1],
[0,0,2],
[0,0,1],
[0,0,3],
[0,0,3],
[0,2,2],
[0,2,1],
[2,2,1],
[0,2,3],
[0,2,2]
]
[0, 0, 2],
[0, 1, 2],
[0, 1, 1],
[0, 0, 2],
[0, 0, 1],
[0, 0, 3],
[0, 0, 3],
[0, 2, 2],
[0, 2, 1],
[2, 2, 1],
[0, 2, 3],
[0, 2, 2]
]
cols = 10
col_rule_len = 2
col_rules = [
[2,1],
[1,3],
[2,4],
[3,4],
[0,4],
[0,3],
[0,3],
[0,3],
[0,2],
[0,2]
]
[2, 1],
[1, 3],
[2, 4],
[3, 4],
[0, 4],
[0, 3],
[0, 3],
[0, 3],
[0, 2],
[0, 2]
]
if __name__ == '__main__':
if len(sys.argv) > 1:
file = sys.argv[1]
execfile(file)
main(rows, row_rule_len, row_rules,
cols, col_rule_len, col_rules)
if len(sys.argv) > 1:
file = sys.argv[1]
execfile(file)
main(rows, row_rule_len, row_rules,
cols, col_rule_len, col_rules)

View File

@@ -49,7 +49,8 @@
to about 1 second'
http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html
* 'Comet: regular constraint, a much faster Nonogram with the regular constraint,
* 'Comet: regular constraint, a much faster Nonogram with the regular
constraint,
some OPL models, and more'
http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html
@@ -61,7 +62,8 @@
Note: nonogram_create_automaton2.mzn is the preferred model
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -120,9 +122,9 @@ def regular(x, Q, S, d, q0, F):
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
@@ -134,6 +136,8 @@ def regular(x, Q, S, d, q0, F):
# Make a transition (automaton) matrix from a
# single pattern, e.g. [3,2,1]
#
def make_transition_matrix(pattern):
p_len = len(pattern)
@@ -160,27 +164,26 @@ def make_transition_matrix(pattern):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states-1:
if c < num_states - 1:
c += 1
tmp[c] = 0
t_matrix[num_states-1][0] = num_states
t_matrix[num_states-1][1] = 0
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i+1
t_matrix[i][1] = i+2
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
else:
if i < num_states-1:
if tmp[i+1] == 1:
if i < num_states - 1:
if tmp[i + 1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i+2
t_matrix[i][1] = i + 2
else:
t_matrix[i][0] = i+2
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
# print 'The states:'
# for i in range(num_states):
# for j in range(2):
@@ -194,6 +197,8 @@ def make_transition_matrix(pattern):
# check each rule by creating an automaton
# and regular
#
def check_rule(rules, y):
solver = y[0].solver()
@@ -209,13 +214,12 @@ def check_rule(rules, y):
# Note: we cannot use 0 since it's the failing state
initial_state = 1
accepting_states = [n_states] # This is the last state
accepting_states = [n_states] # This is the last state
regular(y, n_states, input_max, transition_fn,
initial_state, accepting_states)
def main(rows, row_rule_len, row_rules,
cols, col_rule_len, col_rules):
@@ -248,19 +252,17 @@ def main(rows, row_rule_len, row_rules,
for i in range(rows):
board_label.append(board[i, j])
#
# constraints
#
for i in range(rows):
check_rule([row_rules[i][j] for j in range(row_rule_len)],
[board[i,j] for j in range(cols)])
[board[i, j] for j in range(cols)])
for j in range(cols):
check_rule([col_rules[j][k] for k in range(col_rule_len)],
[board[i, j] for i in range(rows)])
#
# solution and search
#
@@ -299,7 +301,6 @@ def main(rows, row_rule_len, row_rules,
print 'WallTime:', solver.WallTime(), 'ms'
#
# Default problem
#
@@ -309,34 +310,34 @@ def main(rows, row_rule_len, row_rules,
rows = 12
row_rule_len = 3
row_rules = [
[0,0,2],
[0,1,2],
[0,1,1],
[0,0,2],
[0,0,1],
[0,0,3],
[0,0,3],
[0,2,2],
[0,2,1],
[2,2,1],
[0,2,3],
[0,2,2]
]
[0, 0, 2],
[0, 1, 2],
[0, 1, 1],
[0, 0, 2],
[0, 0, 1],
[0, 0, 3],
[0, 0, 3],
[0, 2, 2],
[0, 2, 1],
[2, 2, 1],
[0, 2, 3],
[0, 2, 2]
]
cols = 10
col_rule_len = 2
col_rules = [
[2,1],
[1,3],
[2,4],
[3,4],
[0,4],
[0,3],
[0,3],
[0,3],
[0,2],
[0,2]
]
[2, 1],
[1, 3],
[2, 4],
[3, 4],
[0, 4],
[0, 3],
[0, 3],
[0, 3],
[0, 2],
[0, 2]
]
if __name__ == '__main__':

View File

@@ -49,7 +49,8 @@
to about 1 second'
http://www.hakank.org/constraint_programming_blog/2009/03/comet_nonogram_improved_solvin_1.html
* 'Comet: regular constraint, a much faster Nonogram with the regular constraint,
* 'Comet: regular constraint, a much faster Nonogram with the regular
constraint,
some OPL models, and more'
http://www.hakank.org/constraint_programming_blog/2009/02/comet_regular_constraint_a_muc_1.html
@@ -61,7 +62,8 @@
Note: nonogram_create_automaton2.mzn is the preferred model
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -83,12 +85,12 @@ def make_transition_tuples(pattern):
# this is for handling 0-clues. It generates
# just the minimal state
if num_states == 0:
tuples.Insert3(1, 0, 1);
tuples.Insert3(1, 0, 1)
return (tuples, 1)
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0];
tmp = [0]
c = 0
for pattern_index in range(p_len):
tmp.extend([1] * pattern[pattern_index])
@@ -153,7 +155,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
for i in range(rows):
board_label.append(board[i, j])
#
# constraints
#
@@ -163,7 +164,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
for j in range(cols):
check_rule(col_rules[j], [board[i, j] for i in range(rows)])
#
# solution and search
#
@@ -203,7 +203,6 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
print 'WallTime:', solver.WallTime(), 'ms'
#
# Default problem
#
@@ -213,34 +212,34 @@ def main(rows, row_rule_len, row_rules, cols, col_rule_len, col_rules):
rows = 12
row_rule_len = 3
row_rules = [
[0,0,2],
[0,1,2],
[0,1,1],
[0,0,2],
[0,0,1],
[0,0,3],
[0,0,3],
[0,2,2],
[0,2,1],
[2,2,1],
[0,2,3],
[0,2,2]
]
[0, 0, 2],
[0, 1, 2],
[0, 1, 1],
[0, 0, 2],
[0, 0, 1],
[0, 0, 3],
[0, 0, 3],
[0, 2, 2],
[0, 2, 1],
[2, 2, 1],
[0, 2, 3],
[0, 2, 2]
]
cols = 10
col_rule_len = 2
col_rules = [
[2,1],
[1,3],
[2,4],
[3,4],
[0,4],
[0,3],
[0,3],
[0,3],
[0,2],
[0,2]
]
[2, 1],
[1, 3],
[2, 4],
[3, 4],
[0, 4],
[0, 3],
[0, 3],
[0, 3],
[0, 2],
[0, 2]
]
if __name__ == '__main__':

View File

@@ -64,144 +64,143 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
import string
from ortools.constraint_solver import pywrapcp
def main(m=3, n=6, minimize_val=0):
# Create the solver.
solver = pywrapcp.Solver('Nontransitive dice')
# Create the solver.
solver = pywrapcp.Solver("Nontransitive dice")
#
# data
#
print "number of dice:", m
print "number of sides:", n
#
# data
#
print "number of dice:", m
print "number of sides:", n
#
# declare variables
#
#
# declare variables
#
dice = {}
dice = {}
for i in range(m):
for j in range(n):
dice[(i, j)] = solver.IntVar(1, n * 2, "dice(%i,%i)" % (i, j))
dice_flat = [dice[(i, j)] for i in range(m) for j in range(n)]
comp = {}
for i in range(m):
for j in range(2):
comp[(i, j)] = solver.IntVar(0, n * n, "comp(%i,%i)" % (i, j))
comp_flat = [comp[(i, j)] for i in range(m) for j in range(2)]
# The following variables are for summaries or objectives
gap = [solver.IntVar(0, n * n, "gap(%i)" % i) for i in range(m)]
gap_sum = solver.IntVar(0, m * n * n, "gap_sum")
max_val = solver.IntVar(0, n * 2, "max_val")
max_win = solver.IntVar(0, n * n, "max_win")
# number of occurrences of each value of the dice
counts = [solver.IntVar(0, n * m, "counts(%i)" % i) for i in range(n * 2 + 1)]
#
# constraints
#
# number of occurrences for each number
solver.Add(solver.Distribute(dice_flat, range(n * 2 + 1), counts))
solver.Add(max_win == solver.Max(comp_flat))
solver.Add(max_val == solver.Max(dice_flat))
# order of the number of each die, lowest first
[solver.Add(dice[(i, j)] <= dice[(i, j + 1)])
for i in range(m) for j in range(n - 1)]
# nontransitivity
[comp[i, 0] > comp[i, 1] for i in range(m)],
# probability gap
[solver.Add(gap[i] == comp[i, 0] - comp[i, 1]) for i in range(m)]
[solver.Add(gap[i] > 0) for i in range(m)]
solver.Add(gap_sum == solver.Sum(gap))
# and now we roll...
# Number of wins for [A vs B, B vs A]
for d in range(m):
b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d + 1) % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d % m, 0] == solver.Sum(b1))
b2 = [solver.IsGreaterVar(dice[(d + 1) % m, r1], dice[d % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d % m, 1] == solver.Sum(b2))
# objective
if minimize_val != 0:
print "Minimizing max_val"
objective = solver.Minimize(max_val, 1)
# other experiments
# objective = solver.Maximize(max_win, 1)
# objective = solver.Maximize(gap_sum, 1)
#
# solution and search
#
db = solver.Phase(dice_flat + comp_flat,
solver.INT_VAR_DEFAULT,
solver.ASSIGN_MIN_VALUE)
if minimize_val:
solver.NewSearch(db, [objective])
else:
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "gap_sum:", gap_sum.Value()
print "gap:", [gap[i].Value() for i in range(m)]
print "max_val:", max_val.Value()
print "max_win:", max_win.Value()
print "dice:"
for i in range(m):
for j in range(n):
dice[(i,j)] = solver.IntVar(1, n*2, 'dice(%i,%i)' % (i, j))
dice_flat = [dice[(i,j)] for i in range(m) for j in range(n)]
comp = {}
for j in range(n):
print dice[(i, j)].Value(),
print
print "comp:"
for i in range(m):
for j in range(2):
comp[(i,j)] = solver.IntVar(0, n*n, 'comp(%i,%i)' % (i, j))
comp_flat = [comp[(i,j)] for i in range(m) for j in range(2)]
# The following variables are for summaries or objectives
gap = [solver.IntVar(0, n*n, "gap(%i)"%i) for i in range(m)]
gap_sum = solver.IntVar(0, m*n*n, "gap_sum")
max_val = solver.IntVar(0, n*2, "max_val")
max_win = solver.IntVar(0, n*n, "max_win")
# number of occurrences of each value of the dice
counts = [solver.IntVar(0,n*m,"counts(%i)" %i) for i in range(n*2+1)]
#
# constraints
#
# number of occurrences for each number
solver.Add(solver.Distribute(dice_flat, range(n*2+1), counts))
solver.Add(max_win == solver.Max(comp_flat))
solver.Add(max_val == solver.Max(dice_flat))
# order of the number of each die, lowest first
[ solver.Add(dice[(i,j)] <= dice[(i,j+1)])
for i in range(m) for j in range(n-1)]
# nontransitivity
[ comp[i,0] > comp[i,1] for i in range(m)],
# probability gap
[solver.Add(gap[i] == comp[i,0] - comp[i,1]) for i in range(m)]
[solver.Add(gap[i] > 0) for i in range(m)]
solver.Add(gap_sum == solver.Sum(gap))
# and now we roll...
# Number of wins for [A vs B, B vs A]
for d in range(m):
b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d+1) % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d%m,0] == solver.Sum(b1))
b2 = [solver.IsGreaterVar(dice[(d+1) % m, r1], dice[d % m, r2])
for r1 in range(n) for r2 in range(n)]
solver.Add(comp[d%m,1] == solver.Sum(b2))
# objective
if minimize_val != 0:
print "Minimizing max_val"
objective = solver.Minimize(max_val, 1)
# other experiments
# objective = solver.Maximize(max_win, 1)
# objective = solver.Maximize(gap_sum, 1)
#
# solution and search
#
db = solver.Phase(dice_flat + comp_flat,
solver.INT_VAR_DEFAULT,
solver.ASSIGN_MIN_VALUE)
if minimize_val:
solver.NewSearch(db, [objective])
else:
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "gap_sum:", gap_sum.Value()
print "gap:", [gap[i].Value() for i in range(m)]
print "max_val:", max_val.Value()
print "max_win:", max_win.Value()
print "dice:"
for i in range(m):
for j in range(n):
print dice[(i,j)].Value(),
print
print "comp:"
for i in range(m):
for j in range(2):
print comp[(i,j)].Value(),
print
print "counts:", [counts[i].Value() for i in range(n*2+1)]
print
num_solutions += 1
solver.EndSearch()
for j in range(2):
print comp[(i, j)].Value(),
print
print "counts:", [counts[i].Value() for i in range(n * 2 + 1)]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
m = 3 # number of dice
n = 6 # number of sides of each die
minimize_val = 0 # Minimizing max value (0: no, 1: yes)
if __name__ == '__main__':
if len(sys.argv) > 1:
m = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
if len(sys.argv) > 3:
minimize_val = string.atoi(sys.argv[3])
main(m, n, minimize_val)
if __name__ == "__main__":
if len(sys.argv) > 1:
m = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
n = string.atoi(sys.argv[2])
if len(sys.argv) > 3:
minimize_val = string.atoi(sys.argv[3])
main(m, n, minimize_val)

View File

@@ -19,81 +19,80 @@
N queens problem.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
def main(n=8):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
# n = 8 # size of board (n x n)
#
# data
#
# n = 8 # size of board (n x n)
# declare variables
q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)]
# declare variables
q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(q))
for i in range(n):
for j in range(i):
solver.Add(q[i] != q[j])
solver.Add(q[i] + i != q[j] + j)
solver.Add(q[i] - i != q[j] - j)
#
# constraints
#
solver.Add(solver.AllDifferent(q))
for i in range(n):
for j in range(i):
solver.Add(q[i] != q[j])
solver.Add(q[i] + i != q[j] + j)
solver.Add(q[i] - i != q[j] - j)
# for i in range(n):
# for j in range(i):
# solver.Add(abs(q[i]-q[j]) != abs(i-j))
# for i in range(n):
# for j in range(i):
# solver.Add(abs(q[i]-q[j]) != abs(i-j))
# symmetry breaking
# solver.Add(q[0] == 0)
# symmetry breaking
# solver.Add(q[0] == 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([q[i] for i in range(n)])
#
# solution and search
#
solution = solver.Assignment()
solution.Add([q[i] for i in range(n)])
collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# search_log = solver.SearchLog(100, x[0])
solver.Solve(solver.Phase([q[i] for i in range(n)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
qval = [collector.Value(s, q[i]) for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print
collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# search_log = solver.SearchLog(100, x[0])
solver.Solve(solver.Phase([q[i] for i in range(n)],
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE),
[collector])
num_solutions = collector.SolutionCount()
print "num_solutions: ", num_solutions
if num_solutions > 0:
for s in range(num_solutions):
qval = [collector.Value(s, q[i]) for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
else:
print "No solutions found"
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
else:
print "No solutions found"
n = 8
if __name__ == '__main__':
main(n)
if __name__ == "__main__":
main(n)

View File

@@ -22,80 +22,80 @@
the solutions.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
def main(n=8):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
# n = 8 # size of board (n x n)
#
# data
#
# n = 8 # size of board (n x n)
# declare variables
q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)]
# declare variables
q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(q))
#
# constraints
#
solver.Add(solver.AllDifferent(q))
for i in range(n):
for j in range(i):
solver.Add(q[i] != q[j])
solver.Add(q[i] + i != q[j] + j)
solver.Add(q[i] - i != q[j] - j)
# for i in range(n):
# for j in range(i):
# solver.Add(abs(q[i]-q[j]) != abs(i-j))
# symmetry breaking
# solver.Add(q[0] == 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([q[i] for i in range(n)])
# db: DecisionBuilder
db = solver.Phase([q[i] for i in range(n)],
# solver.CHOOSE_FIRST_UNBOUND,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
qval = [q[i].Value() for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(i):
solver.Add(q[i] != q[j])
solver.Add(q[i] + i != q[j] + j)
solver.Add(q[i] - i != q[j] - j)
# for i in range(n):
# for j in range(i):
# solver.Add(abs(q[i]-q[j]) != abs(i-j))
# symmetry breaking
# solver.Add(q[0] == 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add([q[i] for i in range(n)])
# db: DecisionBuilder
db = solver.Phase([q[i] for i in range(n)],
# solver.CHOOSE_FIRST_UNBOUND,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
qval = [q[i].Value() for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print
num_solutions += 1
solver.EndSearch()
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
n = 8
if __name__ == '__main__':
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)
if __name__ == "__main__":
if len(sys.argv) > 1:
n = string.atoi(sys.argv[1])
main(n)

View File

@@ -24,89 +24,88 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string
import sys
import string
from ortools.constraint_solver import pywrapcp
def main(n=8, num_sol=0, print_sol=1):
# Create the solver.
solver = pywrapcp.Solver('n-queens')
# Create the solver.
solver = pywrapcp.Solver("n-queens")
#
# data
#
print "n:", n
print "num_sol:", num_sol
print "print_sol:", print_sol
#
# data
#
print "n:", n
print "num_sol:", num_sol
print "print_sol:", print_sol
# declare variables
q = [solver.IntVar(0,n-1, 'x%i' % i) for i in range(n)]
# declare variables
q = [solver.IntVar(0, n - 1, "x%i" % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(q))
solver.Add(solver.AllDifferent([q[i]+i for i in range(n)]))
solver.Add(solver.AllDifferent([q[i]-i for i in range(n)]))
#
# constraints
#
solver.Add(solver.AllDifferent(q))
solver.Add(solver.AllDifferent([q[i] + i for i in range(n)]))
solver.Add(solver.AllDifferent([q[i] - i for i in range(n)]))
# symmetry breaking
# solver.Add(q[0] == 0)
# symmetry breaking
# solver.Add(q[0] == 0)
#
# search
#
db = solver.Phase(q,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_CENTER_VALUE)
#
# search
#
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
if print_sol:
qval = [q[i].Value() for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print
num_solutions += 1
if num_sol > 0 and num_solutions >= num_sol:
break
db = solver.Phase(q,
solver.CHOOSE_MIN_SIZE_LOWEST_MAX,
solver.ASSIGN_CENTER_VALUE)
solver.EndSearch()
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
if print_sol:
qval = [q[i].Value() for i in range(n)]
print "q:", qval
for i in range(n):
for j in range(n):
if qval[i] == j:
print "Q",
else:
print "_",
print
print
num_solutions += 1
if num_sol > 0 and num_solutions >= num_sol:
break
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime(), "ms"
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime(), "ms"
n = 8
num_sol = 0
print_sol = 1
if __name__ == '__main__':
if len(sys.argv) > 1:
n = int(sys.argv[1])
if len(sys.argv) > 2:
num_sol = int(sys.argv[2])
if len(sys.argv) > 3:
print_sol = int(sys.argv[3])
if __name__ == "__main__":
if len(sys.argv) > 1:
n = int(sys.argv[1])
if len(sys.argv) > 2:
num_sol = int(sys.argv[2])
if len(sys.argv) > 3:
print_sol = int(sys.argv[3])
main(n, num_sol, print_sol)
main(n, num_sol, print_sol)
# print_sol = False
# show_all = False
# for n in range(1000,1001):
# print
# main(n, num_sol, print_sol)
# print_sol = False
# show_all = False
# for n in range(1000,1001):
# print
# main(n, num_sol, print_sol)

View File

@@ -25,7 +25,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -52,217 +53,214 @@ from collections import defaultdict
# d : transition matrix
# q0: initial state
# F : accepting states
def regular(x, Q, S, d, q0, F):
solver = x[0].solver()
solver = x[0].solver()
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q+1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i-1][j])
d2.append(row)
# Comet: int d2[0..Q, 1..S]
d2 = []
for i in range(Q + 1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i - 1][j])
d2.append(row)
d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)]
d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
m = 0
n = len(x)
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1)))
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(
a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))
def main():
# Create the solver.
solver = pywrapcp.Solver('Nurse rostering using regular')
# Create the solver.
solver = pywrapcp.Solver('Nurse rostering using regular')
#
# data
#
#
# data
#
# Note: If you change num_nurses or num_days,
# please also change the constraints
# on nurse_stat and/or day_stat.
num_nurses = 7
num_days = 14
# Note: If you change num_nurses or num_days,
# please also change the constraints
# on nurse_stat and/or day_stat.
num_nurses = 7
num_days = 14
day_shift = 1
night_shift = 2
off_shift = 3
shifts = [day_shift, night_shift, off_shift]
day_shift = 1
night_shift = 2
off_shift = 3
shifts = [day_shift, night_shift, off_shift]
# the DFA (for regular)
n_states = 6
input_max = 3
initial_state = 1 # 0 is for the failing state
accepting_states = [1,2,3,4,5,6]
# the DFA (for regular)
n_states = 6
input_max = 3
initial_state = 1 # 0 is for the failing state
accepting_states = [1, 2, 3, 4, 5, 6]
transition_fn = [
# d,n,o
[2,3,1], # state 1
[4,4,1], # state 2
[4,5,1], # state 3
[6,6,1], # state 4
[6,0,1], # state 5
[0,0,1] # state 6
]
transition_fn = [
# d,n,o
[2, 3, 1], # state 1
[4, 4, 1], # state 2
[4, 5, 1], # state 3
[6, 6, 1], # state 4
[6, 0, 1], # state 5
[0, 0, 1] # state 6
]
days = ['d','n','o'] # for presentation
days = ['d', 'n', 'o'] # for presentation
#
# declare variables
#
x = {}
for i in range(num_nurses):
for j in range(num_days):
x[i,j] = solver.IntVar(shifts, 'x[%i,%i]'% (i,j))
x_flat = [x[i,j] for i in range(num_nurses) for j in range(num_days)]
# summary of the nurses
nurse_stat = [solver.IntVar(0, num_days, 'nurse_stat[%i]'%i)
for i in range(num_nurses)]
# summary of the shifts per day
day_stat = {}
for i in range(num_days):
for j in shifts:
day_stat[i,j] = solver.IntVar(0, num_nurses, 'day_stat[%i,%i]'% (i,j))
day_stat_flat = [day_stat[i,j] for i in range(num_days) for j in shifts]
#
# constraints
#
for i in range(num_nurses):
reg_input = [x[i,j] for j in range(num_days)]
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# Statistics and constraints for each nurse
#
for i in range(num_nurses):
# number of worked days (day or night shift)
b = [solver.IsEqualCstVar(x[i,j], day_shift) +
solver.IsEqualCstVar(x[i,j], night_shift)
for j in range(num_days)]
solver.Add(nurse_stat[i] == solver.Sum(b))
# Each nurse must work between 7 and 10
# days during this period
solver.Add(nurse_stat[i] >= 7)
solver.Add(nurse_stat[i] <= 10)
#
# Statistics and constraints for each day
#
#
# declare variables
#
x = {}
for i in range(num_nurses):
for j in range(num_days):
for t in shifts:
b = [solver.IsEqualCstVar(x[i,j], t)
for i in range(num_nurses)]
solver.Add(day_stat[j,t] == solver.Sum(b))
x[i, j] = solver.IntVar(shifts, 'x[%i,%i]' % (i, j))
#
# Some constraints for this day:
#
# Note: We have a strict requirements of
# the number of shifts.
# Using atleast constraints is much harder
# in this model.
#
if j % 7 == 5 or j % 7 == 6:
# special constraints for the weekends
solver.Add(day_stat[j,day_shift] == 2)
solver.Add(day_stat[j,night_shift] == 1)
solver.Add(day_stat[j,off_shift] == 4 )
else:
# workdays:
x_flat = [x[i, j] for i in range(num_nurses) for j in range(num_days)]
# - exactly 3 on day shift
solver.Add(day_stat[j,day_shift] == 3)
# - exactly 2 on night
solver.Add(day_stat[j,night_shift] == 2)
# - exactly 1 off duty
solver.Add(day_stat[j,off_shift] == 2 )
# summary of the nurses
nurse_stat = [solver.IntVar(0, num_days, 'nurse_stat[%i]' % i)
for i in range(num_nurses)]
# summary of the shifts per day
day_stat = {}
for i in range(num_days):
for j in shifts:
day_stat[i, j] = solver.IntVar(0, num_nurses, 'day_stat[%i,%i]' % (i, j))
day_stat_flat = [day_stat[i, j] for i in range(num_days) for j in shifts]
#
# constraints
#
for i in range(num_nurses):
reg_input = [x[i, j] for j in range(num_days)]
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# Statistics and constraints for each nurse
#
for i in range(num_nurses):
# number of worked days (day or night shift)
b = [solver.IsEqualCstVar(x[i, j], day_shift) +
solver.IsEqualCstVar(x[i, j], night_shift)
for j in range(num_days)]
solver.Add(nurse_stat[i] == solver.Sum(b))
# Each nurse must work between 7 and 10
# days during this period
solver.Add(nurse_stat[i] >= 7)
solver.Add(nurse_stat[i] <= 10)
#
# Statistics and constraints for each day
#
for j in range(num_days):
for t in shifts:
b = [solver.IsEqualCstVar(x[i, j], t)
for i in range(num_nurses)]
solver.Add(day_stat[j, t] == solver.Sum(b))
#
# solution and search
# Some constraints for this day:
#
db = solver.Phase(day_stat_flat + x_flat + nurse_stat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
# Note: We have a strict requirements of
# the number of shifts.
# Using atleast constraints is much harder
# in this model.
#
if j % 7 == 5 or j % 7 == 6:
# special constraints for the weekends
solver.Add(day_stat[j, day_shift] == 2)
solver.Add(day_stat[j, night_shift] == 1)
solver.Add(day_stat[j, off_shift] == 4)
else:
# workdays:
solver.NewSearch(db)
# - exactly 3 on day shift
solver.Add(day_stat[j, day_shift] == 3)
# - exactly 2 on night
solver.Add(day_stat[j, night_shift] == 2)
# - exactly 1 off duty
solver.Add(day_stat[j, off_shift] == 2)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
#
# solution and search
#
db = solver.Phase(day_stat_flat + x_flat + nurse_stat,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE)
for i in range(num_nurses):
print 'Nurse%i: ' % i,
this_day_stat = defaultdict(int)
for j in range(num_days):
d = days[x[i,j].Value()-1]
this_day_stat[d] += 1
print d,
print ' day_stat:', [(d, this_day_stat[d]) for d in this_day_stat],
print 'total:', nurse_stat[i].Value(), 'workdays'
print
solver.NewSearch(db)
print 'Statistics per day:'
for j in range(num_days):
print 'Day%2i: ' % j,
for t in shifts:
print day_stat[j,t].Value(),
print
print
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
# We just show 2 solutions
if num_solutions >= 2:
break
solver.EndSearch()
for i in range(num_nurses):
print 'Nurse%i: ' % i,
this_day_stat = defaultdict(int)
for j in range(num_days):
d = days[x[i, j].Value() - 1]
this_day_stat[d] += 1
print d,
print ' day_stat:', [(d, this_day_stat[d]) for d in this_day_stat],
print 'total:', nurse_stat[i].Value(), 'workdays'
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'Statistics per day:'
for j in range(num_days):
print 'Day%2i: ' % j,
for t in shifts:
print day_stat[j, t].Value(),
print
print
# We just show 2 solutions
if num_solutions >= 2:
break
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -53,64 +53,67 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
def minus(solver, x, y, z):
solver.Add(z == abs(x - y))
solver.Add(z == abs(x - y))
def main():
# Create the solver.
solver = pywrapcp.Solver('Olympic')
# Create the solver.
solver = pywrapcp.Solver('Olympic')
#
# data
#
n = 10
#
# data
#
n = 10
#
# declare variables
#
Vars = [solver.IntVar(1, n, 'Vars[%i]' % i) for i in range(n)]
X1,X2,X3,X4,X5,X6,X7,X8,X9,X10 = Vars
#
# declare variables
#
Vars = [solver.IntVar(1, n, 'Vars[%i]' % i) for i in range(n)]
X1, X2, X3, X4, X5, X6, X7, X8, X9, X10 = Vars
#
# constraints
#
solver.Add(solver.AllDifferent(Vars))
#
# constraints
#
solver.Add(solver.AllDifferent(Vars))
solver.Add(X1 == 3)
minus(solver, X2, X3, X1)
minus(solver, X4, X5, X2)
minus(solver, X5, X6, X3)
minus(solver, X7, X8, X4)
minus(solver, X8, X9, X5)
minus(solver, X9, X10, X6)
solver.Add(X1 == 3)
minus(solver, X2, X3, X1)
minus(solver, X4, X5, X2)
minus(solver, X5, X6, X3)
minus(solver, X7, X8, X4)
minus(solver, X8, X9, X5)
minus(solver, X9, X10, X6)
#
# solution and search
#
db = solver.Phase(Vars,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
#
# solution and search
#
db = solver.Phase(Vars,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'Vars:', [Vars[i].Value() for i in range(n)]
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'Vars:', [Vars[i].Value() for i in range(n)]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -29,7 +29,8 @@
* Gecode: http://hakank.org/gecode/organize_day.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -38,83 +39,84 @@ from ortools.constraint_solver import pywrapcp
#
# No overlapping of tasks s1 and s2
#
def no_overlap(solver, s1, d1, s2, d2):
b1 = solver.IsLessOrEqualVar(s1 + d1, s2) # s1 + d1 <= s2
b2 = solver.IsLessOrEqualVar(s2 + d2, s1) # s2 + d2 <= s1
solver.Add(b1 + b2 >= 1)
b1 = solver.IsLessOrEqualVar(s1 + d1, s2) # s1 + d1 <= s2
b2 = solver.IsLessOrEqualVar(s2 + d2, s1) # s2 + d2 <= s1
solver.Add(b1 + b2 >= 1)
def main():
# Create the solver.
solver = pywrapcp.Solver('Organizing a day')
# Create the solver.
solver = pywrapcp.Solver('Organizing a day')
#
# data
#
n = 4
#
# data
#
n = 4
tasks = range(n)
work, mail, shop, bank = tasks
durations = [4,1,2,1]
tasks = range(n)
work, mail, shop, bank = tasks
durations = [4, 1, 2, 1]
# task [i,0] must be finished before task [i,1]
before_tasks = [
[bank, shop],
[mail, work]
]
# task [i,0] must be finished before task [i,1]
before_tasks = [
[bank, shop],
[mail, work]
]
# the valid times of the day
begin = 9
end = 17
# the valid times of the day
begin = 9
end = 17
#
# declare variables
#
begins = [solver.IntVar(begin, end, 'begins[%i]% % i') for i in tasks]
ends = [solver.IntVar(begin, end, 'ends[%i]% % i') for i in tasks]
#
# declare variables
#
begins = [solver.IntVar(begin, end, 'begins[%i]% % i') for i in tasks]
ends = [solver.IntVar(begin, end, 'ends[%i]% % i') for i in tasks]
#
# constraints
#
for i in tasks:
solver.Add(ends[i] == begins[i] + durations[i])
#
# constraints
#
for i in tasks:
solver.Add(ends[i] == begins[i] + durations[i])
for i in tasks:
for j in tasks:
if i < j:
no_overlap(solver,
begins[i], durations[i],
begins[j], durations[j])
for i in tasks:
for j in tasks:
if i < j:
no_overlap(solver,
begins[i], durations[i],
begins[j], durations[j])
# specific constraints
for (before, after) in before_tasks:
solver.Add(ends[before] <= begins[after])
# specific constraints
for (before, after) in before_tasks:
solver.Add(ends[before] <= begins[after])
solver.Add(begins[work] >= 11)
solver.Add(begins[work] >= 11)
#
# solution and search
#
db = solver.Phase(begins + ends,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
#
# solution and search
#
db = solver.Phase(begins + ends,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'begins:', [begins[i].Value() for i in tasks]
print 'ends:', [ends[i].Value() for i in tasks]
print
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'begins:', [begins[i].Value() for i in tasks]
print 'ends:', [ends[i].Value() for i in tasks]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -31,7 +31,8 @@
* Comet: http://hakank.org/comet/p_median.co
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -40,91 +41,91 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('P-median problem')
# Create the solver.
solver = pywrapcp.Solver('P-median problem')
#
# data
#
p = 2
#
# data
#
p = 2
num_customers = 4
customers = range(num_customers)
Albert, Bob, Chris, Daniel = customers
num_warehouses = 3
warehouses = range(num_warehouses)
Santa_Clara, San_Jose, Berkeley = warehouses
num_customers = 4
customers = range(num_customers)
Albert, Bob, Chris, Daniel = customers
num_warehouses = 3
warehouses = range(num_warehouses)
Santa_Clara, San_Jose, Berkeley = warehouses
demand = [100,80,80,70]
distance = [
[ 2, 10, 50],
[ 2, 10, 52],
[50, 60, 3],
[40, 60, 1]
]
demand = [100, 80, 80, 70]
distance = [
[2, 10, 50],
[2, 10, 52],
[50, 60, 3],
[40, 60, 1]
]
#
# declare variables
#
open = [solver.IntVar(warehouses, 'open[%i]% % i')
for w in warehouses]
ship = {}
#
# declare variables
#
open = [solver.IntVar(warehouses, 'open[%i]% % i')
for w in warehouses]
ship = {}
for c in customers:
for w in warehouses:
ship[c, w] = solver.IntVar(0, 1, 'ship[%i,%i]' % (c, w))
ship_flat = [ship[c, w]
for c in customers
for w in warehouses]
z = solver.IntVar(0, 1000, 'z')
#
# constraints
#
z_sum = solver.Sum([demand[c] * distance[c][w] * ship[c, w]
for c in customers
for w in warehouses])
solver.Add(z == z_sum)
for c in customers:
s = solver.Sum([ship[c, w]
for w in warehouses])
solver.Add(s == 1)
solver.Add(solver.Sum(open) == p)
for c in customers:
for w in warehouses:
solver.Add(ship[c, w] <= open[w])
# objective
objective = solver.Minimize(z, 1)
#
# solution and search
#
db = solver.Phase(open + ship_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'z:', z.Value()
print 'open:', [open[w].Value() for w in warehouses]
for c in customers:
for w in warehouses:
ship[c,w] = solver.IntVar(0, 1,'ship[%i,%i]' % (c,w))
ship_flat = [ship[c,w]
for c in customers
for w in warehouses]
for w in warehouses:
print ship[c, w].Value(),
print
print
z = solver.IntVar(0, 1000, 'z')
#
# constraints
#
z_sum = solver.Sum([demand[c]*distance[c][w]*ship[c,w]
for c in customers
for w in warehouses])
solver.Add(z == z_sum)
for c in customers:
s = solver.Sum([ship[c,w]
for w in warehouses])
solver.Add(s == 1)
solver.Add(solver.Sum(open) == p)
for c in customers:
for w in warehouses:
solver.Add(ship[c,w] <= open[w])
# objective
objective = solver.Minimize(z, 1)
#
# solution and search
#
db = solver.Phase(open + ship_flat,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "z:", z.Value()
print 'open:', [open[w].Value() for w in warehouses]
for c in customers:
for w in warehouses:
print ship[c,w].Value(),
print
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -57,110 +57,114 @@
* SICStus : http://hakank.org/sicstus/pandigital_numbers.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import string, sys
import string
import sys
from ortools.constraint_solver import pywrapcp
#
# converts a number (s) <-> an array of integers (t) in the specific base.
#
def toNum(solver, t, s, base):
tlen = len(t)
solver.Add(s == solver.Sum([(base**(tlen-i-1))*t[i] for i in range(tlen)]))
tlen = len(t)
solver.Add(
s == solver.Sum([(base ** (tlen - i - 1)) * t[i] for i in range(tlen)]))
def main(base=10, start=1, len1=1, len2=4):
# Create the solver.
solver = pywrapcp.Solver('Pandigital numbers')
# Create the solver.
solver = pywrapcp.Solver("Pandigital numbers")
#
# data
#
max_d = base-1
x_len = max_d + 1 - start
max_num = base**4-1
#
# data
#
max_d = base - 1
x_len = max_d + 1 - start
max_num = base ** 4 - 1
#
# declare variables
#
num1 = solver.IntVar(0, max_num, 'num1')
num2 = solver.IntVar(0, max_num, 'num2')
res = solver.IntVar(0, max_num, 'res')
#
# declare variables
#
num1 = solver.IntVar(0, max_num, "num1")
num2 = solver.IntVar(0, max_num, "num2")
res = solver.IntVar(0, max_num, "res")
x = [solver.IntVar(start, max_d, 'x[%i]' % i) for i in range(x_len)]
x = [solver.IntVar(start, max_d, "x[%i]" % i) for i in range(x_len)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
toNum(solver, [x[i] for i in range(len1)], num1, base)
toNum(solver, [x[i] for i in range(len1,len1+len2)], num2, base)
toNum(solver, [x[i] for i in range(len1+len2,x_len)], res, base)
toNum(solver, [x[i] for i in range(len1)], num1, base)
toNum(solver, [x[i] for i in range(len1, len1 + len2)], num2, base)
toNum(solver, [x[i] for i in range(len1 + len2, x_len)], res, base)
solver.Add(num1*num2 == res)
solver.Add(num1 * num2 == res)
# no number must start with 0
solver.Add(x[0] > 0)
solver.Add(x[len1] > 0)
solver.Add(x[len1+len2] > 0)
# no number must start with 0
solver.Add(x[0] > 0)
solver.Add(x[len1] > 0)
solver.Add(x[len1 + len2] > 0)
# symmetry breaking
solver.Add(num1 < num2)
# symmetry breaking
solver.Add(num1 < num2)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num1)
solution.Add(num2)
solution.Add(res)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solution.Add(num1)
solution.Add(num2)
solution.Add(res)
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_DEFAULT)
solver.NewSearch(db)
num_solutions = 0
solutions = []
while solver.NextSolution():
print_solution([x[i].Value() for i in range(x_len)], len1, len2, x_len)
num_solutions += 1
solver.NewSearch(db)
num_solutions = 0
solutions = []
while solver.NextSolution():
print_solution([x[i].Value() for i in range(x_len)], len1, len2, x_len)
num_solutions += 1
solver.EndSearch()
solver.EndSearch()
if 0 and num_solutions > 0:
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
if 0 and num_solutions > 0:
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
def print_solution(x,len1,len2,x_len):
print "".join([str(x[i]) for i in range(len1)]), "*",
print "".join([str(x[i]) for i in range(len1,len1+len2)]), "=",
print "".join([str(x[i]) for i in range(len1+len2,x_len)])
def print_solution(x, len1, len2, x_len):
print "".join([str(x[i]) for i in range(len1)]), "*",
print "".join([str(x[i]) for i in range(len1, len1 + len2)]), "=",
print "".join([str(x[i]) for i in range(len1 + len2, x_len)])
base = 10
start = 1
if __name__ == '__main__':
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
start = string.atoi(sys.argv[2])
if __name__ == "__main__":
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
if len(sys.argv) > 2:
start = string.atoi(sys.argv[2])
x_len = base-1 + 1-start
for len1 in range(1+(x_len)):
for len2 in range(1+(x_len)):
if x_len > len1 + len2:
main(base, start, len1, len2)
x_len = base - 1 + 1 - start
for len1 in range(1 + (x_len)):
for len2 in range(1 + (x_len)):
if x_len > len1 + len2:
main(base, start, len1, len2)

View File

@@ -43,7 +43,8 @@
* SICStus: http://hakank.org/sicstus/photo_problem.pl
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -54,101 +55,100 @@ from ortools.constraint_solver import pywrapcp
def main(show_all_max=0):
# Create the solver.
solver = pywrapcp.Solver('Photo problem')
# Create the solver.
solver = pywrapcp.Solver("Photo problem")
#
# data
#
persons = ["Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul"]
n = len(persons)
preferences = [
# 0 1 2 3 4 5 6
# B C D F G M P
[ 0,0,0,0,1,1,0], # Betty 0
[ 1,0,0,0,1,0,0], # Chris 1
[ 0,0,0,0,0,0,0], # Donald 2
[ 0,0,1,0,0,1,0], # Fred 3
[ 0,0,0,0,0,0,0], # Gary 4
[ 0,0,0,0,0,0,0], # Mary 5
[ 0,0,1,1,0,0,0] # Paul 6
]
#
# data
#
persons = ["Betty", "Chris", "Donald", "Fred", "Gary", "Mary", "Paul"]
n = len(persons)
preferences = [
# 0 1 2 3 4 5 6
# B C D F G M P
[0, 0, 0, 0, 1, 1, 0], # Betty 0
[1, 0, 0, 0, 1, 0, 0], # Chris 1
[0, 0, 0, 0, 0, 0, 0], # Donald 2
[0, 0, 1, 0, 0, 1, 0], # Fred 3
[0, 0, 0, 0, 0, 0, 0], # Gary 4
[0, 0, 0, 0, 0, 0, 0], # Mary 5
[0, 0, 1, 1, 0, 0, 0] # Paul 6
]
print """Preferences:
print """Preferences:
1. Betty wants to stand next to Gary and Mary.
2. Chris wants to stand next to Betty and Gary.
3. Fred wants to stand next to Mary and Donald.
4. Paul wants to stand next to Fred and Donald.
"""
#
# declare variables
#
positions = [solver.IntVar(0, n-1, "positions[%i]" % i) for i in range(n)]
#
# declare variables
#
positions = [solver.IntVar(0, n - 1, "positions[%i]" % i) for i in range(n)]
# successful preferences
z = solver.IntVar(0, n*n, 'z')
# successful preferences
z = solver.IntVar(0, n * n, "z")
#
# constraints
#
solver.Add(solver.AllDifferent(positions))
#
# constraints
#
solver.Add(solver.AllDifferent(positions))
# calculate all the successful preferences
b = [solver.IsEqualCstVar(abs(positions[i]-positions[j]),1)
for i in range(n) for j in range(n) if preferences[i][j] == 1]
solver.Add(z == solver.Sum(b))
# calculate all the successful preferences
b = [solver.IsEqualCstVar(abs(positions[i] - positions[j]), 1)
for i in range(n) for j in range(n) if preferences[i][j] == 1]
solver.Add(z == solver.Sum(b))
#
# Symmetry breaking (from the Oz page):
# Fred is somewhere left of Betty
solver.Add(positions[3] < positions[0])
#
# Symmetry breaking (from the Oz page):
# Fred is somewhere left of Betty
solver.Add(positions[3] < positions[0])
# objective
objective = solver.Maximize(z, 1)
if show_all_max != 0:
print "Showing all maximum solutions (z == 6).\n"
solver.Add(z == 6)
# objective
objective = solver.Maximize(z, 1)
if show_all_max != 0:
print "Showing all maximum solutions (z == 6).\n"
solver.Add(z == 6)
#
# search and result
#
db = solver.Phase(positions,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
#
# search and result
#
db = solver.Phase(positions,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE)
if show_all_max == 0:
solver.NewSearch(db, [objective])
else:
solver.NewSearch(db)
if show_all_max == 0:
solver.NewSearch(db, [objective])
else:
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print "z:", z.Value()
p = [positions[i].Value() for i in range(n)]
num_solutions = 0
while solver.NextSolution():
print "z:", z.Value()
p = [positions[i].Value() for i in range(n)]
print " ".join([persons[j]
for i in range(n) for j in range(n) if p[j] == i])
print "Successful preferences:"
for i in range(n):
for j in range(n):
if preferences[i][j] == 1 and abs(p[i]-p[j])==1:
print "\t", persons[i], persons[j]
print
num_solutions += 1
solver.EndSearch()
print " ".join([persons[j]
for i in range(n) for j in range(n) if p[j] == i])
print "Successful preferences:"
for i in range(n):
for j in range(n):
if preferences[i][j] == 1 and abs(p[i] - p[j]) == 1:
print "\t", persons[i], persons[j]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
num_solutions += 1
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
show_all_max = 0 # show all maximal solutions
if __name__ == '__main__':
if len(sys.argv) > 1:
show_all_max = 1
main(show_all_max)
if __name__ == "__main__":
if len(sys.argv) > 1:
show_all_max = 1
main(show_all_max)

View File

@@ -36,7 +36,8 @@
* Gecode: http://www.hakank.org/gecode/place_number_puzzle.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -44,91 +45,89 @@ import sys
import string
from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Place number')
# Create the solver.
solver = pywrapcp.Solver("Place number")
# data
m = 32
n = 8
# Note: this is 1-based for compatibility (and lazyness)
graph = [
[1,2],
[1,3],
[1,4],
[2,1],
[2,3],
[2,5],
[2,6],
[3,2],
[3,4],
[3,6],
[3,7],
[4,1],
[4,3],
[4,6],
[4,7],
[5,2],
[5,3],
[5,6],
[5,8],
[6,2],
[6,3],
[6,4],
[6,5],
[6,7],
[6,8],
[7,3],
[7,4],
[7,6],
[7,8],
[8,5],
[8,6],
[8,7]
]
# data
m = 32
n = 8
# Note: this is 1-based for compatibility (and lazyness)
graph = [
[1, 2],
[1, 3],
[1, 4],
[2, 1],
[2, 3],
[2, 5],
[2, 6],
[3, 2],
[3, 4],
[3, 6],
[3, 7],
[4, 1],
[4, 3],
[4, 6],
[4, 7],
[5, 2],
[5, 3],
[5, 6],
[5, 8],
[6, 2],
[6, 3],
[6, 4],
[6, 5],
[6, 7],
[6, 8],
[7, 3],
[7, 4],
[7, 6],
[7, 8],
[8, 5],
[8, 6],
[8, 7]
]
# declare variables
x = [solver.IntVar(1, n, "x%i" % i) for i in range(n)]
# declare variables
x = [solver.IntVar(1, n, "x%i"%i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
for i in range(m):
# Note: make 0-based
solver.Add(abs(
x[graph[i][0] - 1] - x[graph[i][1] - 1]) > 1)
# symmetry breaking
solver.Add(x[0] < x[n - 1])
#
# constraints
#
solver.Add(solver.AllDifferent(x))
for i in range(m):
# Note: make 0-based
solver.Add( abs(
x[graph[i][0]-1]-x[graph[i][1]-1]) > 1
)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
# symmetry breaking
solver.Add(x[0] < x[n-1])
collector = solver.AllSolutionCollector(solution)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
collector = solver.AllSolutionCollector(solution)
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))]
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MIN_VALUE),
[collector])
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
num_solutions = collector.SolutionCount()
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
if __name__ == '__main__':
main()
if __name__ == "__main__":
main()

View File

@@ -51,7 +51,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -59,76 +60,73 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Post office problem')
# Create the solver.
solver = pywrapcp.Solver('Post office problem')
#
# data
#
#
# data
#
# days 0..6, monday 0
n = 7
days = range(n)
need = [17, 13, 15, 19, 14, 16, 11]
# days 0..6, monday 0
n = 7
days = range(n)
need = [17, 13, 15, 19, 14, 16, 11]
# Total cost for the 5 day schedule.
# Base cost per day is 100.
# Working saturday is 100 extra
# Working sunday is 200 extra.
cost = [500, 600, 800, 800, 800, 800, 700]
# Total cost for the 5 day schedule.
# Base cost per day is 100.
# Working saturday is 100 extra
# Working sunday is 200 extra.
cost = [500, 600, 800, 800, 800, 800, 700]
#
# variables
#
#
# variables
#
# No. of workers starting at day i
x = [solver.IntVar(0, 100, 'x[%i]' % i) for i in days]
# No. of workers starting at day i
x = [solver.IntVar(0, 100, 'x[%i]'%i) for i in days]
total_cost = solver.IntVar(0, 20000, 'total_cost')
num_workers = solver.IntVar(0, 100, 'num_workers')
total_cost = solver.IntVar(0, 20000, 'total_cost')
num_workers = solver.IntVar(0, 100, 'num_workers')
#
# constraints
#
solver.Add(total_cost == solver.ScalProd(x, cost))
solver.Add(num_workers == solver.Sum(x))
#
# constraints
#
solver.Add(total_cost == solver.ScalProd(x, cost))
solver.Add(num_workers == solver.Sum(x))
for i in days:
s = solver.Sum([x[j] for j in days
if j != (i + 5) % n and j != (i + 6) % n])
solver.Add(s >= need[i])
for i in days:
s = solver.Sum([x[j] for j in days
if j != (i+5) % n and j != (i+6) % n])
solver.Add(s >= need[i])
# objective
objective = solver.Minimize(total_cost, 1)
# objective
objective = solver.Minimize(total_cost, 1)
#
# search and result
#
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MIN_VALUE)
#
# search and result
#
db = solver.Phase(x,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_MIN_VALUE
)
solver.NewSearch(db, [objective])
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'num_workers:', num_workers.Value()
print 'total_cost:', total_cost.Value()
print 'x:', [x[i].Value() for i in days]
num_solutions = 0
solver.EndSearch()
while solver.NextSolution():
num_solutions += 1
print 'num_workers:', num_workers.Value()
print 'total_cost:', total_cost.Value()
print 'x:', [x[i].Value() for i in days]
solver.EndSearch()
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime()
if __name__ == '__main__':
main()
main()

View File

@@ -19,13 +19,15 @@
From the OPL model production.mod.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.linear_solver import pywraplp
def main(sol = 'GLPK'):
def main(sol='GLPK'):
# Create the solver.
@@ -38,7 +40,6 @@ def main(sol = 'GLPK'):
solver = pywraplp.Solver('CoinsGridCLP',
pywraplp.Solver.CLP_LINEAR_PROGRAMMING)
#
# data
#
@@ -53,33 +54,34 @@ def main(sol = 'GLPK'):
resources = ['flour', 'eggs']
num_resources = len(resources)
consumption = [ [0.5, 0.2], [0.4, 0.4], [0.3, 0.6] ]
capacity = [ 20, 40 ]
demand = [ 100, 200, 300 ]
inside_cost = [0.6, 0.8, 0.3 ]
consumption = [[0.5, 0.2], [0.4, 0.4], [0.3, 0.6]]
capacity = [20, 40]
demand = [100, 200, 300]
inside_cost = [0.6, 0.8, 0.3]
outside_cost = [0.8, 0.9, 0.4]
#
# declare variables
#
inside = [solver.NumVar(0, 10000, 'inside[%i]' % p )
inside = [solver.NumVar(0, 10000, 'inside[%i]' % p)
for p in range(num_products)]
outside = [solver.NumVar(0, 10000, 'outside[%i]' % p )
outside = [solver.NumVar(0, 10000, 'outside[%i]' % p)
for p in range(num_products)]
# to minimize
z = solver.Sum([inside_cost[p] * inside[p] + outside_cost[p] * outside[p]
for p in range(num_products)])
for p in range(num_products)])
#
# constraints
#
for r in range(num_resources):
solver.Add(solver.Sum(
[consumption[p][r]*inside[p] for p in range(num_products)]) <= capacity[r])
[consumption[p][r] * inside[p]
for p in range(num_products)]) <= capacity[r])
for p in range(num_products):
solver.Add(inside[p] + outside[p] >= demand[p])
solver.Add(inside[p] + outside[p] >= demand[p])
objective = solver.Minimize(z)
@@ -89,8 +91,8 @@ def main(sol = 'GLPK'):
print 'z = ', solver.Objective().Value()
for p in range(num_products):
print products[p], ': inside:', inside[p].SolutionValue(), '(ReducedCost:', inside[p].ReducedCost(), ')',
print 'outside:', outside[p].SolutionValue(), ' (ReducedCost:', outside[p].ReducedCost(), ')'
print products[p], ': inside:', inside[p].SolutionValue(), '(ReducedCost:', inside[p].ReducedCost(), ')',
print 'outside:', outside[p].SolutionValue(), ' (ReducedCost:', outside[p].ReducedCost(), ')'
print

View File

@@ -14,7 +14,6 @@
"""MaxFlow and MinCostFlow examples."""
from google.apputils import app
from ortools.graph import pywrapgraph

View File

@@ -24,12 +24,15 @@
Ivars Peterson "Completing Latin Squares"
http://www.maa.org/mathland/mathtrek_5_8_00.html
'''
Using only the numbers 1, 2, 3, and 4, arrange four sets of these numbers into
Using only the numbers 1, 2, 3, and 4, arrange four sets of these numbers
into
a four-by-four array so that no column or row contains the same two numbers.
The result is known as a Latin square.
...
The so-called quasigroup completion problem concerns a table that is correctly
but only partially filled in. The question is whether the remaining blanks in
The so-called quasigroup completion problem concerns a table that is
correctly
but only partially filled in. The question is whether the remaining blanks
in
the table can be filled in to obtain a complete Latin square (or a proper
quasigroup multiplication table).
'''
@@ -47,7 +50,8 @@
* Zinc: http://hakank.org/minizinc/quasigroup_completion.zinc
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -63,153 +67,150 @@ default_puzzle = [
[4, X, X, 2, X],
[X, 4, X, X, X],
[X, X, 5, X, 1]
]
]
def main(puzzle="", n=0):
# Create the solver.
solver = pywrapcp.Solver('Quasigroup completion')
# Create the solver.
solver = pywrapcp.Solver("Quasigroup completion")
#
# data
#
#
# data
#
if puzzle == "":
puzzle = default_puzzle
n = default_n
if puzzle == "":
puzzle = default_puzzle
n = default_n
print "Problem:"
print_game(puzzle, n,n)
print "Problem:"
print_game(puzzle, n, n)
# declare variables
x = {}
for i in range(n):
for j in range(n):
x[(i, j)] = solver.IntVar(1, n, "x %i %i" % (i, j))
# declare variables
x = {}
xflat = [x[(i, j)] for i in range(n) for j in range(n)]
#
# constraints
#
#
# set the clues
#
for i in range(n):
for j in range(n):
if puzzle[i][j] > X:
solver.Add(x[i, j] == puzzle[i][j])
#
# rows and columns must be different
#
for i in range(n):
solver.Add(solver.AllDifferent([x[i, j] for j in range(n)]))
solver.Add(solver.AllDifferent([x[j, i] for j in range(n)]))
#
# solution and search
#
solution = solver.Assignment()
solution.Add(xflat)
# This version prints out the solution directly, and
# don't collect them as solver.FirstSolutionCollector(solution) do
# (db: DecisionBuilder)
db = solver.Phase(xflat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Solution %i" % num_solutions
xval = [x[(i, j)].Value() for i in range(n) for j in range(n)]
for i in range(n):
for j in range(n):
x[(i,j)] = solver.IntVar(1,n, 'x %i %i' % (i, j))
xflat = [x[(i,j)] for i in range(n) for j in range(n)]
#
# constraints
#
#
# set the clues
#
for i in range(n):
for j in range(n):
if puzzle[i][j] > X:
solver.Add(x[i,j] == puzzle[i][j])
#
# rows and columns must be different
#
for i in range(n):
solver.Add(solver.AllDifferent([x[i,j] for j in range(n)]))
solver.Add(solver.AllDifferent([x[j,i] for j in range(n)]))
#
# solution and search
#
solution = solver.Assignment()
solution.Add(xflat)
# This version prints out the solution directly, and
# don't collect them as solver.FirstSolutionCollector(solution) do
# (db: DecisionBuilder)
db = solver.Phase(xflat,
solver.INT_VAR_SIMPLE,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "Solution %i" % num_solutions
xval = [x[(i,j)].Value() for i in range(n) for j in range(n)]
for i in range(n):
for j in range(n):
print xval[i*n+j],
print
print
solver.EndSearch()
if num_solutions == 0:
print "No solutions found"
# # Note: AllSolution may take very much RAM, hence I choose to
# # show just the first solution.
# # collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)],
# solver.CHOOSE_FIRST_UNBOUND,
# solver.ASSIGN_MIN_VALUE),
# [collector])
#
# num_solutions = collector.SolutionCount()
# print "\nnum_solutions: ", num_solutions
# if num_solutions > 0:
# print "\nJust showing the first solution..."
# for s in range(num_solutions):
# xval = [collector.Value(s, x[(i,j)]) for i in range(n) for j in range(n)]
# for i in range(n):
# for j in range(n):
# print xval[i*n+j],
# print
# print
for j in range(n):
print xval[i * n + j],
print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
solver.EndSearch()
if num_solutions == 0:
print "No solutions found"
# # Note: AllSolution may take very much RAM, hence I choose to
# # show just the first solution.
# # collector = solver.AllSolutionCollector(solution)
# collector = solver.FirstSolutionCollector(solution)
# solver.Solve(solver.Phase([x[(i,j)] for i in range(n) for j in range(n)],
# solver.CHOOSE_FIRST_UNBOUND,
# solver.ASSIGN_MIN_VALUE),
# [collector])
#
# num_solutions = collector.SolutionCount()
# print "\nnum_solutions: ", num_solutions
# if num_solutions > 0:
# print "\nJust showing the first solution..."
# for s in range(num_solutions):
# xval = [collector.Value(s, x[(i,j)]) for i in range(n) for j in range(n)]
# for i in range(n):
# for j in range(n):
# print xval[i*n+j],
# print
# print
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
#
# Read a problem instance from a file
#
def read_problem(file):
f = open(file, 'r')
n = int(f.readline())
game = []
for i in range(n):
x = f.readline()
row_x = (x.rstrip()).split(" ")
row = [0]*n
for j in range(n):
if row_x[j] == ".":
tmp = 0
else:
tmp = int(row_x[j])
row[j] = tmp
game.append(row)
return [game, n]
f = open(file, "r")
n = int(f.readline())
game = []
for i in range(n):
x = f.readline()
row_x = (x.rstrip()).split(" ")
row = [0] * n
for j in range(n):
if row_x[j] == ".":
tmp = 0
else:
tmp = int(row_x[j])
row[j] = tmp
game.append(row)
return [game, n]
def print_board(x, rows, cols):
for i in range(rows):
for j in range(cols):
print "% 2s" % x[i,j],
print ''
for i in range(rows):
for j in range(cols):
print "% 2s" % x[i, j],
print ""
def print_game(game, rows, cols):
for i in range(rows):
for j in range(cols):
print "% 2s" % game[i][j],
print ''
for i in range(rows):
for j in range(cols):
print "% 2s" % game[i][j],
print ""
if __name__ == "__main__":
if __name__ == '__main__':
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[game, n] = read_problem(file)
main(game, n)
else:
main()
if len(sys.argv) > 1:
file = sys.argv[1]
print "Problem instance from", file
[game, n] = read_problem(file)
main(game, n)
else:
main()

View File

@@ -22,7 +22,6 @@ flavors of constraint programming interfaces.
"""
from ortools.constraint_solver import pywrapcp

View File

@@ -34,7 +34,8 @@
using an array of size 10.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -63,50 +64,50 @@ from ortools.constraint_solver import pywrapcp
# F : accepting states
def regular(x, Q, S, d, q0, F):
solver = x[0].solver()
solver = x[0].solver()
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
assert Q > 0, 'regular: "Q" must be greater than zero'
assert S > 0, 'regular: "S" must be greater than zero'
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# d2 is the same as d, except we add one extra transition for
# each possible input; each extra transition is from state zero
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
# int d2[0..Q, 1..S];
d2 = []
for i in range(Q+1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i-1][j])
d2.append(row)
# int d2[0..Q, 1..S];
d2 = []
for i in range(Q + 1):
row = []
for j in range(S):
if i == 0:
row.append(0)
else:
row.append(d[i - 1][j])
d2.append(row)
d2_flatten = [d2[i][j] for i in range(Q+1) for j in range(S)]
d2_flatten = [d2[i][j] for i in range(Q + 1) for j in range(S)]
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
m = 0
n = len(x)
# If x has index set m..n, then a[m-1] holds the initial state
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q+1, 'a[%i]' % i) for i in range(m, n+1)]
a = [solver.IntVar(0, Q + 1, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(a[i+1] == solver.Element(d2_flatten, ((a[i])*S)+(x[i]-1)))
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
solver.Add(x[i] <= S)
# Determine a[i+1]: a[i+1] == d2[a[i], x[i]]
solver.Add(
a[i + 1] == solver.Element(d2_flatten, ((a[i]) * S) + (x[i] - 1)))
#
@@ -115,111 +116,110 @@ def regular(x, Q, S, d, q0, F):
#
def make_transition_matrix(pattern):
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states-1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states - 1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
t_matrix[num_states-1][0] = num_states
t_matrix[num_states-1][1] = 0
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i+1
t_matrix[i][1] = i+2
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
else:
if i < num_states - 1:
if tmp[i + 1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i + 2
else:
if i < num_states-1:
if tmp[i+1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i+2
else:
t_matrix[i][0] = i+2
t_matrix[i][1] = 0
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print
return t_matrix
return t_matrix
def main():
# Create the solver.
solver = pywrapcp.Solver('Regular test')
# Create the solver.
solver = pywrapcp.Solver('Regular test')
#
# data
#
#
# data
#
this_len = 10
pp = [3,2,1]
this_len = 10
pp = [3, 2, 1]
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
accepting_states = [n_states]
accepting_states = [n_states]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)]
num_solutions += 1
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)]
num_solutions += 1
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -34,7 +34,8 @@
using an array of size 10.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -73,7 +74,7 @@ def regular(x, Q, S, d, q0, F):
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
d2 = pywrapcp.IntTupleSet(3);
d2 = pywrapcp.IntTupleSet(3)
for i in range(Q + 1):
for j in range(S):
if i == 0:
@@ -85,15 +86,15 @@ def regular(x, Q, S, d, q0, F):
# (q0), and a[i+1] holds the state we're in after processing
# x[i]. If a[n] is in F, then we succeed (ie. accept the
# string).
x_range = range(0,len(x))
x_range = range(0, len(x))
m = 0
n = len(x)
a = [solver.IntVar(0, Q, 'a[%i]' % i) for i in range(m, n+1)]
a = [solver.IntVar(0, Q, 'a[%i]' % i) for i in range(m, n + 1)]
# Check that the final state is in F
# Check that the final state is in F
solver.Add(solver.MemberCt(a[-1], F))
# First state is q0
# First state is q0
solver.Add(a[m] == q0)
for i in x_range:
solver.Add(x[i] >= 1)
@@ -108,111 +109,110 @@ def regular(x, Q, S, d, q0, F):
#
def make_transition_matrix(pattern):
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states - 1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states - 1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
else:
if i < num_states - 1:
if tmp[i + 1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i + 2
else:
if i < num_states - 1:
if tmp[i+1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i + 2
else:
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print
return t_matrix
return t_matrix
def main():
# Create the solver.
solver = pywrapcp.Solver('Regular test')
# Create the solver.
solver = pywrapcp.Solver('Regular test')
#
# data
#
#
# data
#
this_len = 10
pp = [3,2,1]
this_len = 10
pp = [3, 2, 1]
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
accepting_states = [n_states]
accepting_states = [n_states]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)]
num_solutions += 1
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)]
num_solutions += 1
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -34,7 +34,8 @@
using an array of size 10.
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -73,7 +74,7 @@ def regular(x, Q, S, d, q0, F):
# to state zero. This allows us to continue even if we hit a
# non-accepted input.
d2 = pywrapcp.IntTupleSet(3);
d2 = pywrapcp.IntTupleSet(3)
for i in range(Q + 1):
for j in range(1, S + 1):
if i == 0:
@@ -87,113 +88,114 @@ def regular(x, Q, S, d, q0, F):
# Make a transition (automaton) matrix from a
# single pattern, e.g. [3,2,1]
#
def make_transition_matrix(pattern):
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
p_len = len(pattern)
print 'p_len:', p_len
num_states = p_len + sum(pattern)
print 'num_states:', num_states
t_matrix = []
for i in range(num_states):
row = []
for j in range(2):
row.append(0)
t_matrix.append(row)
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states-1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
# convert pattern to a 0/1 pattern for easy handling of
# the states
tmp = [0 for i in range(num_states)]
c = 0
tmp[c] = 0
for i in range(p_len):
for j in range(pattern[i]):
c += 1
tmp[c] = 1
if c < num_states - 1:
c += 1
tmp[c] = 0
print 'tmp:', tmp
t_matrix[num_states - 1][0] = num_states
t_matrix[num_states - 1][1] = 0
t_matrix[num_states-1][0] = num_states
t_matrix[num_states-1][1] = 0
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i+1
t_matrix[i][1] = i+2
for i in range(num_states):
if tmp[i] == 0:
t_matrix[i][0] = i + 1
t_matrix[i][1] = i + 2
else:
if i < num_states - 1:
if tmp[i + 1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i + 2
else:
if i < num_states-1:
if tmp[i+1] == 1:
t_matrix[i][0] = 0
t_matrix[i][1] = i+2
else:
t_matrix[i][0] = i+2
t_matrix[i][1] = 0
t_matrix[i][0] = i + 2
t_matrix[i][1] = 0
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print 'The states:'
for i in range(num_states):
for j in range(2):
print t_matrix[i][j],
print
print
return t_matrix
return t_matrix
def main():
# Create the solver.
solver = pywrapcp.Solver('Regular test')
# Create the solver.
solver = pywrapcp.Solver('Regular test')
#
# data
#
#
# data
#
this_len = 10
pp = [3,2,1]
this_len = 10
pp = [3, 2, 1]
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
transition_fn = make_transition_matrix(pp)
n_states = len(transition_fn)
input_max = 2
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
# Note: we use '1' and '2' (rather than 0 and 1)
# since 0 represents the failing state.
initial_state = 1
accepting_states = [n_states]
accepting_states = [n_states]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
# declare variables
reg_input = [solver.IntVar(1, input_max, 'reg_input[%i]' % i)
for i in range(this_len)]
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# constraints
#
regular(reg_input, n_states, input_max, transition_fn,
initial_state, accepting_states)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
#
# solution and search
#
db = solver.Phase(reg_input,
solver.CHOOSE_MIN_SIZE_HIGHEST_MAX,
solver.ASSIGN_MIN_VALUE)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value() - 1 for i in range(this_len)]
num_solutions += 1
num_solutions = 0
while solver.NextSolution():
print 'reg_input:', [reg_input[i].Value()-1 for i in range(this_len)]
num_solutions += 1
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -41,129 +41,131 @@
* MiniZinc: http://www.hakank.org/minizinc/rogo2.mzn
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys, string, re
import sys
import string
import re
from ortools.constraint_solver import pywrapcp
def main(problem, rows, cols, max_steps):
# Create the solver.
solver = pywrapcp.Solver('Rogo grid puzzle')
# Create the solver.
solver = pywrapcp.Solver("Rogo grid puzzle")
#
# data
#
W = 0
B = -1
print "rows: %i cols: %i max_steps: %i" % (rows, cols, max_steps)
#
# data
#
W = 0
B = -1
print "rows: %i cols: %i max_steps: %i" % (rows, cols, max_steps)
problem_flatten = [problem[i][j] for i in range(rows) for j in range(cols)]
max_point = max(problem_flatten)
print "max_point:", max_point
max_sum = sum(problem_flatten)
print "max_sum:", max_sum
problem_flatten = [problem[i][j] for i in range(rows) for j in range(cols)]
max_point = max(problem_flatten)
print "max_point:", max_point
max_sum = sum(problem_flatten)
print "max_sum:", max_sum
print
#
# declare variables
#
# the coordinates
x = [solver.IntVar(0, rows - 1, "x[%i]" % i) for i in range(max_steps)]
y = [solver.IntVar(0, cols - 1, "y[%i]" % i) for i in range(max_steps)]
# the collected points
points = [solver.IntVar(0, max_point, "points[%i]" % i)
for i in range(max_steps)]
# objective: sum of points in the path
sum_points = solver.IntVar(0, max_sum)
#
# constraints
#
# all coordinates must be unique
for s in range(max_steps):
for t in range(s + 1, max_steps):
b1 = solver.IsDifferentVar(x[s], x[t])
b2 = solver.IsDifferentVar(y[s], y[t])
solver.Add(b1 + b2 >= 1)
# calculate the points (to maximize)
for s in range(max_steps):
solver.Add(points[s] == solver.Element(problem_flatten, x[s] * cols + y[s]))
solver.Add(sum_points == sum(points))
# ensure that there are not black cells in
# the path
for s in range(max_steps):
solver.Add(solver.Element(problem_flatten, x[s] * cols + y[s]) != B)
# get the path
for s in range(max_steps - 1):
solver.Add(abs(x[s] - x[s + 1]) + abs(y[s] - y[s + 1]) == 1)
# close the path around the corner
solver.Add(abs(x[max_steps - 1] - x[0]) + abs(y[max_steps - 1] - y[0]) == 1)
# symmetry breaking: the cell with lowest coordinates
# should be in the first step.
for i in range(1, max_steps):
solver.Add(x[0] * cols + y[0] < x[i] * cols + y[i])
# symmetry breaking: second step is larger than
# first step
# solver.Add(x[0]*cols+y[0] < x[1]*cols+y[1])
#
# objective
#
objective = solver.Maximize(sum_points, 1)
#
# solution and search
#
# db = solver.Phase(x + y,
# solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
# solver.ASSIGN_MIN_VALUE)
# Default search
parameters = pywrapcp.DefaultPhaseParameters()
parameters.heuristic_period = 200000
# parameters.var_selection_schema = parameters.CHOOSE_MAX_SUM_IMPACT
parameters.var_selection_schema = parameters.CHOOSE_MAX_AVERAGE_IMPACT # <-
# parameters.var_selection_schema = parameters.CHOOSE_MAX_VALUE_IMPACT
parameters.value_selection_schema = parameters.SELECT_MIN_IMPACT # <-
# parameters.value_selection_schema = parameters.SELECT_MAX_IMPACT
# parameters.initialization_splits = 10
db = solver.DefaultPhase(x + y, parameters)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "sum_points:", sum_points.Value()
print "adding 1 to coords..."
for s in range(max_steps):
print "%i %i" % (x[s].Value() + 1, y[s].Value() + 1)
print
#
# declare variables
#
# the coordinates
x = [solver.IntVar(0, rows-1, "x[%i]"%i) for i in range(max_steps)]
y = [solver.IntVar(0, cols-1, "y[%i]"%i) for i in range(max_steps)]
# the collected points
points = [solver.IntVar(0, max_point, "points[%i]"%i) for i in range(max_steps)]
# objective: sum of points in the path
sum_points = solver.IntVar(0, max_sum)
#
# constraints
#
# all coordinates must be unique
for s in range(max_steps):
for t in range(s+1, max_steps):
b1 = solver.IsDifferentVar(x[s], x[t])
b2 = solver.IsDifferentVar(y[s], y[t])
solver.Add(b1+b2 >= 1)
# calculate the points (to maximize)
for s in range(max_steps):
solver.Add(points[s] == solver.Element(problem_flatten, x[s]*cols+y[s]))
solver.Add(sum_points == sum(points))
# ensure that there are not black cells in
# the path
for s in range(max_steps):
solver.Add(solver.Element(problem_flatten, x[s]*cols+y[s]) != B)
# get the path
for s in range(max_steps-1):
solver.Add(abs(x[s]-x[s+1]) + abs(y[s]-y[s+1]) == 1)
# close the path around the corner
solver.Add(abs(x[max_steps-1]-x[0]) + abs(y[max_steps-1]-y[0]) == 1)
# symmetry breaking: the cell with lowest coordinates
# should be in the first step.
for i in range(1,max_steps):
solver.Add(x[0]*cols+y[0] < x[i]*cols+y[i])
# symmetry breaking: second step is larger than
# first step
# solver.Add(x[0]*cols+y[0] < x[1]*cols+y[1])
#
# objective
#
objective = solver.Maximize(sum_points, 1)
#
# solution and search
#
# db = solver.Phase(x + y,
# solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
# solver.ASSIGN_MIN_VALUE)
# Default search
parameters = pywrapcp.DefaultPhaseParameters()
parameters.heuristic_period = 200000
# parameters.var_selection_schema = parameters.CHOOSE_MAX_SUM_IMPACT
parameters.var_selection_schema = parameters.CHOOSE_MAX_AVERAGE_IMPACT # <-
# parameters.var_selection_schema = parameters.CHOOSE_MAX_VALUE_IMPACT
parameters.value_selection_schema = parameters.SELECT_MIN_IMPACT # <-
# parameters.value_selection_schema = parameters.SELECT_MAX_IMPACT
# parameters.initialization_splits = 10
db = solver.DefaultPhase(x + y, parameters)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print "sum_points:", sum_points.Value()
print "adding 1 to coords..."
for s in range(max_steps):
print "%i %i" % (x[s].Value()+1,y[s].Value()+1)
print
print "\nnum_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print "\nnum_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
# Default problem:
@@ -185,8 +187,8 @@ problem = [
[W, W, W, W, W, W, B, W, 2],
[W, W, 2, B, W, W, W, W, W],
[W, W, W, W, 2, W, W, 1, W]
]
if __name__ == '__main__':
if len(sys.argv) > 1:
execfile(sys.argv[1])
main(problem, rows, cols, max_steps)
]
if __name__ == "__main__":
if len(sys.argv) > 1:
execfile(sys.argv[1])
main(problem, rows, cols, max_steps)

View File

@@ -42,7 +42,8 @@
* Gecode: http://hakank.org/gecode/safe_cracking.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -50,60 +51,57 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Safe cracking puzzle')
# Create the solver.
solver = pywrapcp.Solver('Safe cracking puzzle')
#
# data
#
n = 9
digits = range(1,n+1)
#
# data
#
n = 9
digits = range(1, n + 1)
#
# variables
#
#
# variables
#
LD = [solver.IntVar(digits, 'LD[%i]'%i) for i in range(n)]
C1,C2,C3,C4,C5,C6,C7,C8,C9 = LD
LD = [solver.IntVar(digits, 'LD[%i]' % i) for i in range(n)]
C1, C2, C3, C4, C5, C6, C7, C8, C9 = LD
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
#
# constraints
#
solver.Add(solver.AllDifferent(LD))
solver.Add(C4 - C6 == C7)
solver.Add(C1 * C2 * C3 == C8 + C9)
solver.Add(C2 + C3 + C6 < C8)
solver.Add(C9 < C8)
for i in range(n):
solver.Add(LD[i] != i+1)
solver.Add(C4 - C6 == C7)
solver.Add(C1 * C2 * C3 == C8 + C9)
solver.Add(C2 + C3 + C6 < C8)
solver.Add(C9 < C8)
for i in range(n):
solver.Add(LD[i] != i + 1)
#
# search and result
#
db = solver.Phase(LD,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
#
# search and result
#
db = solver.Phase(LD,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT
)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'LD:', [LD[i].Value() for i in range(n)]
num_solutions = 0
solver.EndSearch()
while solver.NextSolution():
num_solutions += 1
print 'LD:', [LD[i].Value() for i in range(n)]
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -26,7 +26,8 @@
* Gecode: http://hakank.org/gecode/scheduling_speakers.cpp
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
from ortools.constraint_solver import pywrapcp
@@ -34,64 +35,61 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Scheduling speakers')
# Create the solver.
solver = pywrapcp.Solver('Scheduling speakers')
#
# data
#
n = 6 # number of speakers
#
# data
#
n = 6 # number of speakers
# slots available to speak
available = [
# Reasoning:
[3,4,5,6], # 2) the only one with 6 after speaker F -> 1
[3,4], # 5) 3 or 4
[2,3,4,5], # 3) only with 5 after F -> 1 and A -> 6
[2,3,4], # 4) only with 2 after C -> 5 and F -> 1
[3,4], # 5) 3 or 4
[1,2,3,4,5,6] # 1) the only with 1
]
# slots available to speak
available = [
# Reasoning:
[3, 4, 5, 6], # 2) the only one with 6 after speaker F -> 1
[3, 4], # 5) 3 or 4
[2, 3, 4, 5], # 3) only with 5 after F -> 1 and A -> 6
[2, 3, 4], # 4) only with 2 after C -> 5 and F -> 1
[3, 4], # 5) 3 or 4
[1, 2, 3, 4, 5, 6] # 1) the only with 1
]
#
# variables
#
x = [solver.IntVar(1, n, 'x[%i]'%i) for i in range(n)]
#
# variables
#
x = [solver.IntVar(1, n, 'x[%i]' % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
for i in range(n):
solver.Add(solver.MemberCt(x[i], available[i]))
for i in range(n):
solver.Add(solver.MemberCt(x[i], available[i]))
#
# search and result
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT)
#
# search and result
#
db = solver.Phase(x,
solver.INT_VAR_DEFAULT,
solver.INT_VALUE_DEFAULT
)
solver.NewSearch(db)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
num_solutions = 0
solver.EndSearch()
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
solver.EndSearch()
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -57,7 +57,8 @@
- WallTime: 23735 ms (note: without any printing of the solutions)
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
from ortools.constraint_solver import pywrapcp
@@ -65,53 +66,53 @@ from ortools.constraint_solver import pywrapcp
def main():
# Create the solver.
solver = pywrapcp.Solver('Secret Santa problem')
# Create the solver.
solver = pywrapcp.Solver('Secret Santa problem')
#
# data
#
family = [1,1,1,1, 2, 3,3,3,3,3, 4,4]
num_families = max(family)
n = len(family)
#
# data
#
family = [1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 4, 4]
num_families = max(family)
n = len(family)
#
# declare variables
#
x = [solver.IntVar(0, n-1, 'x[%i]' % i) for i in range(n)]
#
# declare variables
#
x = [solver.IntVar(0, n - 1, 'x[%i]' % i) for i in range(n)]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
#
# constraints
#
solver.Add(solver.AllDifferent(x))
# Can't be one own's Secret Santa
# Ensure that there are no fix-point in the array
for i in range(n):
solver.Add(x[i] != i)
# Can't be one own's Secret Santa
# Ensure that there are no fix-point in the array
for i in range(n):
solver.Add(x[i] != i)
# No Secret Santa to a person in the same family
for i in range(n):
solver.Add(family[i] != solver.Element(family, x[i]))
# No Secret Santa to a person in the same family
for i in range(n):
solver.Add(family[i] != solver.Element(family, x[i]))
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
#
# solution and search
#
db = solver.Phase(x,
solver.INT_VAR_SIMPLE,
solver.INT_VALUE_SIMPLE)
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
print
solver.NewSearch(db)
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'x:', [x[i].Value() for i in range(n)]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
if __name__ == '__main__':
main()
main()

View File

@@ -58,7 +58,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
import sys
@@ -67,159 +68,154 @@ from ortools.constraint_solver import pywrapcp
def main(singe=0):
# Create the solver.
solver = pywrapcp.Solver('Secret Santa problem II')
# Create the solver.
solver = pywrapcp.Solver('Secret Santa problem II')
#
# data
#
#
# data
#
#
# The matrix version of earlier rounds.
# M means that no earlier Santa has been assigned.
# Note: Ryan and Mia has the same recipient for years 3 and 4,
# and Ella and John has for year 4.
# This seems to be caused by modification of
# original data.
#
n_no_single = 8
M = n_no_single + 1
rounds_no_single = [
# N A R M El J L Ev
[0, M, 3, M, 1, 4, M, 2], # Noah
[M, 0, 4, 2, M, 3, M, 1], # Ava
[M, 2, 0, M, 1, M, 3, 4], # Ryan
[M, 1, M, 0, 2, M, 3, 4], # Mia
[M, 4, M, 3, 0, M, 1, 2], # Ella
[1, 4, 3, M, M, 0, 2, M], # John
[M, 3, M, 2, 4, 1, 0, M], # Lily
[4, M, 3, 1, M, 2, M, 0] # Evan
]
#
# The matrix version of earlier rounds.
# M means that no earlier Santa has been assigned.
# Note: Ryan and Mia has the same recipient for years 3 and 4,
# and Ella and John has for year 4.
# This seems to be caused by modification of
# original data.
#
n_no_single = 8
M = n_no_single + 1
rounds_no_single = [
# N A R M El J L Ev
[0, M, 3, M, 1, 4, M, 2], # Noah
[M, 0, 4, 2, M, 3, M, 1], # Ava
[M, 2, 0, M, 1, M, 3, 4], # Ryan
[M, 1, M, 0, 2, M, 3, 4], # Mia
[M, 4, M, 3, 0, M, 1, 2], # Ella
[1, 4, 3, M, M, 0, 2, M], # John
[M, 3, M, 2, 4, 1, 0, M], # Lily
[4, M, 3, 1, M, 2, M, 0] # Evan
]
#
# Rounds with a single person (fake data)
#
n_with_single = 9
M = n_with_single + 1
rounds_single = [
# N A R M El J L Ev S
[0, M, 3, M, 1, 4, M, 2, 2], # Noah
[M, 0, 4, 2, M, 3, M, 1, 1], # Ava
[M, 2, 0, M, 1, M, 3, 4, 4], # Ryan
[M, 1, M, 0, 2, M, 3, 4, 3], # Mia
[M, 4, M, 3, 0, M, 1, 2, M], # Ella
[1, 4, 3, M, M, 0, 2, M, M], # John
[M, 3, M, 2, 4, 1, 0, M, M], # Lily
[4, M, 3, 1, M, 2, M, 0, M], # Evan
[1, 2, 3, 4, M, 2, M, M, 0] # Single
]
#
# Rounds with a single person (fake data)
#
n_with_single = 9
M = n_with_single + 1
rounds_single = [
# N A R M El J L Ev S
[0, M, 3, M, 1, 4, M, 2, 2], # Noah
[M, 0, 4, 2, M, 3, M, 1, 1], # Ava
[M, 2, 0, M, 1, M, 3, 4, 4], # Ryan
[M, 1, M, 0, 2, M, 3, 4, 3], # Mia
[M, 4, M, 3, 0, M, 1, 2, M], # Ella
[1, 4, 3, M, M, 0, 2, M, M], # John
[M, 3, M, 2, 4, 1, 0, M, M], # Lily
[4, M, 3, 1, M, 2, M, 0, M], # Evan
[1, 2, 3, 4, M, 2, M, M, 0] # Single
]
if single == 1:
n = n_with_single
Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan, Single = range(n)
rounds = rounds_single
else:
n = n_no_single
Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan = range(n)
rounds = rounds_no_single
if single == 1:
n = n_with_single
Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan, Single = range(n)
rounds = rounds_single
else:
n = n_no_single
Noah, Ava, Ryan, Mia, Ella, John, Lily, Evan = range(n)
rounds = rounds_no_single
M = n + 1
M = n + 1
persons = ['Noah', 'Ava', 'Ryan', 'Mia', 'Ella',
'John', 'Lily', 'Evan', 'Single']
persons = ['Noah', 'Ava', 'Ryan', 'Mia', 'Ella',
'John', 'Lily', 'Evan', 'Single']
spouses = [
Ava, # Noah
Noah, # Ava
Mia, # Rya
Ryan, # Mia
John, # Ella
Ella, # John
Evan, # Lily
Lily, # Evan
-1 # Single has no spouse
]
spouses = [
Ava, # Noah
Noah, # Ava
Mia, # Rya
Ryan, # Mia
John, # Ella
Ella, # John
Evan, # Lily
Lily, # Evan
-1 # Single has no spouse
]
#
# declare variables
#
santas = [solver.IntVar(0, n - 1, 'santas[%i]' % i)
for i in range(n)]
santa_distance = [solver.IntVar(0, M, 'santa_distance[%i]' % i)
for i in range(n)]
# total of 'distance', to maximize
z = solver.IntVar(0, n * n * n, 'z')
#
# constraints
#
solver.Add(solver.AllDifferent(santas))
#
# declare variables
#
santas = [solver.IntVar(0, n-1, 'santas[%i]' % i)
for i in range(n)]
santa_distance = [solver.IntVar(0, M, 'santa_distance[%i]' % i)
for i in range(n)]
solver.Add(z == solver.Sum(santa_distance))
# total of 'distance', to maximize
z = solver.IntVar(0, n*n*n, 'z')
# Can't be one own's Secret Santa
# (i.e. ensure that there are no fix-point in the array.)
for i in range(n):
solver.Add(santas[i] != i)
#
# constraints
#
solver.Add(solver.AllDifferent(santas))
# no Santa for a spouses
for i in range(n):
if spouses[i] > -1:
solver.Add(santas[i] != spouses[i])
solver.Add(z == solver.Sum(santa_distance))
# optimize 'distance' to earlier rounds:
for i in range(n):
solver.Add(santa_distance[i] ==
solver.Element(rounds[i], santas[i]))
# Can't be one own's Secret Santa
# (i.e. ensure that there are no fix-point in the array.)
# cannot be a Secret Santa for the same person
# two years in a row.
for i in range(n):
for j in range(n):
if rounds[i][j] == 1:
solver.Add(santas[i] != j)
# objective
objective = solver.Maximize(z, 1)
#
# solution and search
#
db = solver.Phase(santas,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total distances:', z.Value()
print 'santas:', [santas[i].Value() for i in range(n)]
for i in range(n):
solver.Add(santas[i] != i)
print '%s\tis a Santa to %s (distance %i)' % \
(persons[i],
persons[santas[i].Value()],
santa_distance[i].Value())
# print 'distance:', [santa_distance[i].Value()
# for i in range(n)]
print
# no Santa for a spouses
for i in range(n):
if spouses[i] > -1 :
solver.Add(santas[i] != spouses[i])
# optimize 'distance' to earlier rounds:
for i in range(n):
solver.Add(santa_distance[i] ==
solver.Element(rounds[i], santas[i]))
# cannot be a Secret Santa for the same person
# two years in a row.
for i in range(n):
for j in range(n):
if rounds[i][j] == 1:
solver.Add(santas[i] != j)
# objective
objective = solver.Maximize(z, 1)
#
# solution and search
#
db = solver.Phase(santas,
solver.CHOOSE_MIN_SIZE_LOWEST_MIN,
solver.ASSIGN_CENTER_VALUE)
solver.NewSearch(db, [objective])
num_solutions = 0
while solver.NextSolution():
num_solutions += 1
print 'total distances:', z.Value()
print 'santas:', [santas[i].Value() for i in range(n)]
for i in range(n):
print '%s\tis a Santa to %s (distance %i)' % \
(persons[i],
persons[santas[i].Value()],
santa_distance[i].Value())
# print 'distance:', [santa_distance[i].Value()
# for i in range(n)]
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime(), 'ms'
single = 0
if __name__ == '__main__':
print 'Secret Santas without single'
main(single)
print '\nSecret Santas with single:'
single = 1
main(single)
print 'Secret Santas without single'
main(single)
print '\nSecret Santas with single:'
single = 1
main(single)

View File

@@ -38,7 +38,8 @@
This model was created by Hakan Kjellerstrand (hakank@bonetmail.com)
Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/
Also see my other Google CP Solver models:
http://www.hakank.org/google_or_tools/
"""
@@ -46,71 +47,68 @@ import sys
import string
from ortools.constraint_solver import pywrapcp
def main(base=10):
# Create the solver.
solver = pywrapcp.Solver('Send most money')
# Create the solver.
solver = pywrapcp.Solver('Send most money')
# data
print "base:", base
# data
print 'base:', base
# declare variables
s = solver.IntVar(0,base-1,'s')
e = solver.IntVar(0,base-1,'e')
n = solver.IntVar(0,base-1,'n')
d = solver.IntVar(0,base-1,'d')
m = solver.IntVar(0,base-1,'m')
o = solver.IntVar(0,base-1,'o')
r = solver.IntVar(0,base-1,'r')
y = solver.IntVar(0,base-1,'y')
# declare variables
s = solver.IntVar(0, base - 1, 's')
e = solver.IntVar(0, base - 1, 'e')
n = solver.IntVar(0, base - 1, 'n')
d = solver.IntVar(0, base - 1, 'd')
m = solver.IntVar(0, base - 1, 'm')
o = solver.IntVar(0, base - 1, 'o')
r = solver.IntVar(0, base - 1, 'r')
y = solver.IntVar(0, base - 1, 'y')
x = [s,e,n,d,m,o,r,y]
x = [s, e, n, d, m, o, r, y]
#
# constraints
#
solver.Add(solver.AllDifferent(x))
solver.Add(s * base ** 3 + e * base ** 2 + n * base + d +
m * base ** 3 + o * base ** 2 + r * base + e ==
m * base ** 4 + o * base ** 3 + n * base ** 2 + e * base + y,)
solver.Add(s > 0)
solver.Add(m > 0)
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
#
# constraints
#
solver.Add(solver.AllDifferent(x))
solver.Add( s*base**3 + e*base**2 + n*base + d +
m*base**3 + o*base**2 + r*base + e ==
m*base**4 + o*base**3 + n*base**2 + e*base + y,
)
solver.Add(s > 0)
solver.Add(m > 0)
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE),
[collector])
#
# solution and search
#
solution = solver.Assignment()
solution.Add(x)
num_solutions = collector.SolutionCount()
money_val = 0
for s in range(num_solutions):
print 'x:', [collector.Value(s, x[i]) for i in range(len(x))]
collector = solver.AllSolutionCollector(solution)
solver.Solve(solver.Phase(x,
solver.CHOOSE_FIRST_UNBOUND,
solver.ASSIGN_MAX_VALUE),
[collector])
num_solutions = collector.SolutionCount()
money_val = 0
for s in range(num_solutions):
print "x:", [collector.Value(s, x[i]) for i in range(len(x))]
print
print "num_solutions:", num_solutions
print "failures:", solver.Failures()
print "branches:", solver.Branches()
print "WallTime:", solver.WallTime()
print
print
print 'num_solutions:', num_solutions
print 'failures:', solver.Failures()
print 'branches:', solver.Branches()
print 'WallTime:', solver.WallTime()
print
base = 10
if __name__ == '__main__':
# for base in range(10,30):
# main(base)
if len(sys.argv) > 1:
base=string.atoi(sys.argv[1])
# for base in range(10,30):
# main(base)
if len(sys.argv) > 1:
base = string.atoi(sys.argv[1])
main(base)
main(base)

Some files were not shown because too many files have changed in this diff Show More