Example #1
0
def arithmetic(puzzle="SEND+MORE=MONEY", base=10) -> None:

    problem = re.split(r"[\s+=]", puzzle)

    # remove spaces
    problem = list(filter(lambda w: len(w) > 0, problem))

    letters = {
        letter: facile.variable(range(base))
        for letter in set("".join(problem))
    }

    # expressions
    expr_pb = [[letters[a] for a in word] for word in problem]

    def horner(a: Expression, b: Expression):
        return 10 * a + b

    words = [reduce(horner, word) for word in expr_pb]

    # constraints
    facile.constraint(facile.alldifferent(letters.values()))
    facile.constraint(facile.sum(words[:-1]) == words[-1])

    for word in expr_pb:
        facile.constraint(word[0] > 0)

    assert facile.solve(letters.values())

    # print solutions
    for word, numbers in zip(problem, expr_pb):
        strings = [str(n.value()) for n in numbers]
        print(f"{word} = {''.join(strings)}")
Example #2
0
def arithmetic(puzzle="SEND+MORE=MONEY", base=10):

    problem = re.split("[\s+=]", puzzle)

    # remove spaces
    problem = list(filter(lambda w: len(w) > 0, problem))

    # letters
    letters = {l: fcl.variable(range(base)) for l in set("".join(problem))}

    # expressions
    expr_pb = [[letters[a] for a in word] for word in problem]
    words = [reduce(lambda a, b: 10 * a + b, word) for word in expr_pb]

    # constraints
    fcl.constraint(fcl.alldifferent(letters.values()))
    fcl.constraint(sum(words[:-1]) == words[-1])

    for word in expr_pb:
        fcl.constraint(word[0] > 0)

    assert fcl.solve(letters.values())

    # print solutions
    for word, numbers in zip(problem, expr_pb):
        strings = [str(n.value()) for n in numbers]
        print(word + " = " + "".join(strings))
Example #3
0
def test_nosolution() -> None:
    a, b, c = [facile.variable(0, 1) for _ in range(3)]
    facile.constraint(a != b)
    facile.constraint(b != c)
    facile.constraint(c != a)
    sol = facile.solve([a, b, c])
    assert not sol.solved
Example #4
0
def tile(sizes, bigsize):
    n = len(sizes)
    xs = [facile.variable(0, bigsize - sizes[i]) for i in range(n)]
    ys = [facile.variable(0, bigsize - sizes[i]) for i in range(n)]

    for i in range(n-1):
        for j in range(i+1, n):
            c_left = xs[j] + sizes[j] <= xs[i] # j on the left of i
            c_right = xs[j] >= xs[i] + sizes[i] # j on the right of i
            c_below = ys[j] + sizes[j] <= ys[i] # etc.
            c_above = ys[j] >= ys[i] + sizes[i]
            facile.constraint(c_left | c_right | c_below | c_above)

    # Redundant capacity constraint
    def full_line(xy):
        for i in range(bigsize):
            # equivalent to (xy[j] >= i - sizes[j] + 1) & (xy[j] <= i)
            intersections = \
                    [xy[j].in_interval(i - sizes[j] + 1, i) for j in range(n)]

            scal_prod = sum([s * k for s, k in zip(sizes, intersections)])
            facile.constraint(scal_prod == bigsize)

    full_line(xs)
    full_line(ys)

    if facile.solve(xs + ys, heuristic=facile.Heuristic.Min_min):
        try:
            import matplotlib.pyplot as plt
            import matplotlib.cm as colormap
            from random import random as rand

            fig = plt.figure()
            ax = fig.gca()

            def fill_square(x, y, s):
                plt.fill([x, x, x+s, x+s], [y, y+s, y+s, y],
                         color=colormap.Pastel1(rand()))

            fill_square(0, 0, bigsize)
            for (x, y, s) in zip(xs, ys, sizes):
                fill_square(x.value(), y.value(), s)

            ax.set_xlim((0, bigsize))
            ax.set_ylim((0, bigsize))
            ax.set_aspect(1)
            ax.set_xticks(range(bigsize + 1))
            ax.set_yticks(range(bigsize + 1))
            fig.set_size_inches(7, 7)
            ax.set_frame_on(False)
            plt.pause(10)

        except Exception as e:
            # if matplotlib fails for an unknown reason
            print (e)
            for (x, y, s) in zip(xs, ys, sizes):
                print (x.value(), y.value(), s)
Example #5
0
def tile(sizes, bigsize):
    n = len(sizes)
    xs = [facile.variable(0, bigsize - sizes[i]) for i in range(n)]
    ys = [facile.variable(0, bigsize - sizes[i]) for i in range(n)]

    for i in range(n - 1):
        for j in range(i + 1, n):
            c_left = xs[j] + sizes[j] <= xs[i]  # j on the left of i
            c_right = xs[j] >= xs[i] + sizes[i]  # j on the right of i
            c_below = ys[j] + sizes[j] <= ys[i]  # etc.
            c_above = ys[j] >= ys[i] + sizes[i]
            facile.constraint(c_left | c_right | c_below | c_above)

    # Redundant capacity constraint
    def full_line(xy):
        for i in range(bigsize):
            # equivalent to (xy[j] >= i - sizes[j] + 1) & (xy[j] <= i)
            intersections = \
                    [xy[j].in_interval(i - sizes[j] + 1, i) for j in range(n)]

            scal_prod = sum([s * k for s, k in zip(sizes, intersections)])
            facile.constraint(scal_prod == bigsize)

    full_line(xs)
    full_line(ys)

    if facile.solve(xs + ys, heuristic=facile.Heuristic.Min_min):
        try:
            import matplotlib.pyplot as plt
            import matplotlib.cm as colormap
            from random import random as rand

            fig = plt.figure()
            ax = fig.gca()

            def fill_square(x, y, s):
                plt.fill([x, x, x + s, x + s], [y, y + s, y + s, y],
                         color=colormap.Pastel1(rand()))

            fill_square(0, 0, bigsize)
            for (x, y, s) in zip(xs, ys, sizes):
                fill_square(x.value(), y.value(), s)

            ax.set_xlim((0, bigsize))
            ax.set_ylim((0, bigsize))
            ax.set_aspect(1)
            ax.set_xticks(range(bigsize + 1))
            ax.set_yticks(range(bigsize + 1))
            fig.set_size_inches(7, 7)
            ax.set_frame_on(False)
            plt.pause(10)

        except Exception as e:
            # if matplotlib fails for an unknown reason
            print(e)
            for (x, y, s) in zip(xs, ys, sizes):
                print(x.value(), y.value(), s)
Example #6
0
def n_queens(n: int, *args, **kwargs) -> facile.Solution:
    queens = [facile.variable(range(n)) for i in range(n)]
    diag1 = [queens[i] + i for i in range(n)]
    diag2 = [queens[i] - i for i in range(n)]

    facile.constraint(facile.alldifferent(queens))
    facile.constraint(facile.alldifferent(diag1))
    facile.constraint(facile.alldifferent(diag2))

    return facile.solve(queens, *args, **kwargs)
Example #7
0
def picross_solve(
    lines: list[list[int]],
    columns: list[list[int]],
) -> tuple[facile.Solution, facile.Array]:
    n, m = len(lines), len(columns)
    grid = facile.Array.binary((n, m))

    sol = facile.solve(grid)

    return sol, grid
Example #8
0
def test_magical() -> None:
    array = [facile.variable(range(10)) for i in range(10)]

    for i in range(10):
        sum_ = facile.sum(x == i for x in array)
        facile.constraint(sum_ == array[i])

    solution = facile.solve(array)

    assert solution.solved
    assert solution.solution == [6, 2, 1, 0, 0, 0, 1, 0, 0, 0]
Example #9
0
def test_2d_array() -> None:
    n = 5
    # array = facile.Array.binary((n, n))
    var_array = [[facile.variable(0, 1) for _ in range(n)] for _ in range(n)]
    array = facile.array(np.array(var_array))

    for i in range(n):
        facile.constraint(array[:, i].sum() == 1)
        facile.constraint(array[i, :].sum() == 1)

    x, y = facile.variable(range(n)), facile.variable(range(n))
    facile.constraint(array[x, y] == 1)
    # TODO redundant but necessary to test one of the arguments as a variable
    # facile.constraint(array[:, x].sum() == 1)

    sol = facile.solve([*array])
    assert sol.solved

    sol = facile.solve([*array, x, y])
    assert sol.solved
    *_, x_, y_ = sol.solution
    assert array[x_, y_].value() == 1
Example #10
0
def n_queen(n):
    """Solves the n-queen problem. """
    queens = [variable(0, n - 1) for i in range(n)]
    diag1 = [queens[i] + i for i in range(n)]
    diag2 = [queens[i] - i for i in range(n)]

    constraint(alldifferent(queens))
    constraint(alldifferent(diag1))
    constraint(alldifferent(diag2))

    if solve(queens):
        return [x.value() for x in queens]
    else:
        return None
Example #11
0
def n_queen(n):
    """Solves the n-queen problem. """
    queens = [variable(0, n-1) for i in range(n)]
    diag1 = [queens[i] + i for i in range(n)]
    diag2 = [queens[i] - i for i in range(n)]

    constraint(alldifferent(queens))
    constraint(alldifferent(diag1))
    constraint(alldifferent(diag2))

    if solve(queens):
        return [x.value() for x in queens]
    else:
        return None
Example #12
0
def n_queen(n):
    """Solves the n-queen problem. """

    queens = [variable(range(n)) for i in range(n)]

    # prepare for animation
    def on_bt(nb_bt):
        for i, q in enumerate(queens):
            print(i, q.domain())

    constraint(alldifferent(queens))
    constraint(alldifferent(queens[i] - i for i in range(n)))
    constraint(alldifferent(queens[i] + i for i in range(n)))

    return solve(queens, strategy=queen_strategy, backtrack=True)
Example #13
0
def test_basic_array() -> None:
    var_list = [facile.variable(0, 1) for _ in range(5)]
    array = facile.array(var_list)
    x = facile.variable(range(10))

    msg = "list indices must be integers or slices, not facile.core.Variable"
    with pytest.raises(TypeError, match=msg):
        facile.constraint(var_list[x] == 1)  # type: ignore

    facile.constraint(array[x] == 1)
    facile.constraint(array.sum() == 1)
    facile.constraint(x == 1)

    solution = facile.solve([*array, x])
    assert solution.solved
    assert array.value() == [0, 1, 0, 0, 0]
Example #14
0
def tatami_solve(xmax: int, ymax: int) -> list[facile.Solution]:
    """Solves the tatami problem.

    The variables in the solve_all must be passed in order:
    - x coordinates;
    - y coordinates;
    - xs the size of the tatami on the x axis (1: vertical, 2: horizontal);
    - other variables
    """

    if (xmax * ymax) & 1 == 1:
        raise ValueError(
            f"The room area must be an even number: {xmax * ymax}")
    n = xmax * ymax // 2  # noqa: F841

    # start with a "simple" solve(), then comment the line when things work
    return [facile.solve([], backtrack=True)]
    # the evaluation process expects that you return *all* solutions
    return facile.solve_all([], backtrack=True)
Example #15
0
def test_domains() -> None:
    a = facile.variable(range(320))
    b = facile.variable(range(160))
    c = facile.variable(range(130))
    d = facile.variable(range(130))

    facile.constraint(a + b + c + d == 711)
    assert len(a.domain()) == 26
    assert len(b.domain()) == 26
    assert len(c.domain()) == 26
    assert len(d.domain()) == 26

    facile.constraint(a * b * c * d == 711000000)
    assert len(a.domain()) == 17
    assert len(b.domain()) == 23
    assert len(c.domain()) == 20
    assert len(d.domain()) == 20

    sol = facile.solve([a, b, c, d], backtrack=True)
    assert sol.solved
    assert sol.backtrack == 2
Example #16
0
def lazy_n_queens(n: int, *args, **kwargs) -> facile.Solution:
    queens = [facile.variable(range(n)) for i in range(n)]
    diag1 = [queens[i] + i for i in range(n)]
    diag2 = [queens[i] - i for i in range(n)]

    # facile.constraint(facile.alldifferent(queens))
    for i, q1 in enumerate(queens):
        for q2 in queens[i + 1:]:
            facile.constraint(q1 != q2)

    # facile.constraint(facile.alldifferent(diag1))
    for i, q1 in enumerate(diag1):
        for q2 in diag1[i + 1:]:
            facile.constraint(q1 != q2)

    # facile.constraint(facile.alldifferent(diag2))
    for i, q1 in enumerate(diag2):
        for q2 in diag2[i + 1:]:
            facile.constraint(q1 != q2)

    return facile.solve(queens, *args, **kwargs)
Example #17
0
import facile

# Magical sequence!
# The value inside array[i] is equal to the number of i in array

array = [facile.variable(0,10) for i in range(10)]

for i in range(10):
    facile.constraint(sum([x == i for x in array]) == array[i])

if facile.solve(array):
    print ([v.value() for v in array])

Example #18
0
# -*- coding: utf-8 -*-
"""
Find four numbers such that their sum is 711 and their product is 711000000
"""

from facile import variable, constraint, solve

a = variable(range(0, 330))
b = variable(range(0, 160))
c = variable(range(0, 140))
d = variable(range(0, 140))

constraint(a + b + c + d == 711)
constraint(a * b * c * d == 711000000)

sol = solve([a, b, c, d])
print("Solution found a={}, b={}, c={}, d={}".format(*sol.solution))
Example #19
0
a = facile.variable(range(0, 321))
b = facile.variable(range(0, 161))
c = facile.variable(range(0, 131))
d = facile.variable(range(0, 131))

# Constraints

# The problem
facile.constraint(a + b + c + d == 711)

print("Domains after posting the sum constraint")
for x in [a, b, c, d]:
    domain = x.domain()
    print("  {!r} (size {})".format(domain, len(domain)))

facile.constraint(a * b * c * d == 711000000)

print("\nDomains after posting the mul constraint")
for x in [a, b, c, d]:
    domain = x.domain()
    print("  {!r} (size {})".format(domain, len(domain)))

print()

# Resolution
sol = facile.solve([a, b, c, d], backtrack=True)

# wow ! Only two backtracks !!
print(sol)
print("Solution found: a={}, b={}, c={}, d={}".format(*sol.solution))
Example #20
0
# -*- coding: utf-8 -*-

"""
Basic examples of CSP problems:
    - a ≠ b
    - alldifferent(a, b, c) and a + b <= 2c
"""

from facile import variable, constraint, solve, alldifferent

a = variable(0, 1)
b = variable(0, 1)

constraint(a != b)

if solve([a, b]):
    print ("Solution found a=%d and b=%d" % (a.value(), b.value()))

a = variable(0, 2)
b = variable(0, 2)
c = variable(0, 2)

constraint(alldifferent([a, b, c]))
constraint(a + b <= 2 * c)
if solve([a, b, c]):
    print ("Solution found a=%d, b=%d and c=%d" %
           (a.value(), b.value(), c.value()))
Example #21
0
    s = groups[i].sort()
    for j in range(nb_golfers):
        facile.constraint(s[j] == j//size_group)

    # [2] Use a Global Cardinality Constraint (redundant with [1])
    gcc = groups[i].gcc([(size_group, i) for i in range(nb_groups)])
    facile.constraint(gcc)

# Two golfers do not play in the same group more than once
for g1 in range(nb_golfers):
    for g2 in range(g1+1, nb_golfers):
        g1_with_g2 = [groups[w][g1] == groups[w][g2] for w in range(nb_weeks)]
        facile.constraint(sum(g1_with_g2) <= 1)

# Breaking the symmetries
#  - 0 always in the first group, 1 in a group less than 1, ...
#  - First week (0) a priori chosen

for w in range(nb_weeks):
    for g in range(nb_groups):
        facile.constraint(groups[w][g] <= g)

for g in range(nb_golfers):
    facile.constraint(groups[0][g] == g//size_group)

if (not facile.solve([v for k in groups for v in k ])):
    print ("No solution found")
else:
    for v in groups: print (v.value())

Example #22
0
# Agatha hates everybody except the butler.
constraint(hates[agatha, charles] == 1)
constraint(hates[agatha, agatha] == 1)
constraint(hates[agatha, butler] == 0)

# The butler hates everyone not richer than Aunt Agatha.
#   (richer[i, agatha] = 0) => (hates[butler, i] = 1),
for i in range(n):
    constraint((richer[i, agatha] == 0) <= (hates[butler, i] == 1))

# The butler hates everyone whom Agatha hates.
#   (hates[agatha, i] = 1) => (hates[butler, i] = 1),
for i in range(n):
    constraint((hates[agatha, i] == 1) <= (hates[butler, i] == 1))

# No one hates everyone.
#   (sum j: hates[i, j]) <= 2,
for i in range(n):
    constraint(sum([hates[i, j] for j in range(n)]) <= 2)

# Who killed Agatha?
constraint(victim == agatha)

assert solve(list(hates) + list(richer) + [victim, killer])
killer_value = killer.value()
assert killer_value is not None

msg = "{} killed Agatha."
print(msg.format(["Agatha", "The butler", "Charles"][killer_value]))
Example #23
0
def tiles(sizes, bigsize):
    n = len(sizes)
    xs = [variable(range(bigsize - sizes[i] + 1)) for i in range(n)]
    ys = [variable(range(bigsize - sizes[i] + 1)) for i in range(n)]

    for i in range(n - 1):
        for j in range(i + 1, n):
            c_left = xs[j] + sizes[j] <= xs[i]  # j on the left of i
            c_right = xs[j] >= xs[i] + sizes[i]  # j on the right of i
            c_below = ys[j] + sizes[j] <= ys[i]  # etc.
            c_above = ys[j] >= ys[i] + sizes[i]
            constraint(c_left | c_right | c_below | c_above)

    # Redundant capacity constraint
    def full_line(xy):
        for i in range(bigsize):
            # equivalent to (xy[j] >= i - sizes[j] + 1) & (xy[j] <= i)
            intersections = [
                xy[j].in_interval(i - sizes[j] + 1, i) for j in range(n)
            ]

            scal_prod = sum([s * k for s, k in zip(sizes, intersections)])
            constraint(scal_prod == bigsize)

    full_line(xs)
    full_line(ys)

    gx = Goal.forall(xs, assign="assign", strategy="min_min")
    gy = Goal.forall(ys, assign="assign", strategy="min_min")

    # Now the proper resolution process
    solution = solve(gx & gy, backtrack=True)
    print(solution)
    try:
        import matplotlib.pyplot as plt  # type: ignore

        fig, ax = plt.subplots(figsize=(7, 7))

        def fill_square(x, y, s):
            plt.fill(
                [x, x, x + s, x + s],
                [y, y + s, y + s, y],
                color=plt.get_cmap("tab20")(random()),
            )

        fill_square(0, 0, bigsize)
        for (x, y, s) in zip(xs, ys, sizes):
            fill_square(x.value(), y.value(), s)

        ax.set_xlim((0, bigsize))
        ax.set_ylim((0, bigsize))
        ax.set_aspect(1)
        ax.set_xticks(range(bigsize + 1))
        ax.set_yticks(range(bigsize + 1))
        ax.set_frame_on(False)
        plt.pause(10)

    except ImportError as e:
        # if matplotlib fails for an unknown reason
        print(e)
        for (x, y, s) in zip(xs, ys, sizes):
            print(x.value(), y.value(), s)
Example #24
0
def test_solution() -> None:
    a = facile.variable([0, 1])
    b = facile.variable([0, 1])
    facile.constraint(a != b)
    sol = facile.solve([a, b])
    assert sol.solved
Example #25
0
]

wife = array([variable(range(n)) for i in range(n)])
husband = array([variable(range(n)) for i in range(n)])

# You are your wife's husband, and conversely
for m in range(n):
    constraint(husband[wife[m]] == m)
for w in range(n):
    constraint(wife[husband[w]] == w)

for m in range(n):
    for w in range(n):
        # m prefers this woman to his wife
        c1 = rank_men[m][w] < array(rank_men[m])[wife[m]]
        # w prefers her husband to this man
        c2 = array(rank_women[w])[husband[w]] < rank_women[w][m]
        # alias for c1 => c2
        constraint(c1 <= c2)
        # w prefers this man to her husband
        c3 = rank_women[w][m] < array(rank_women[w])[husband[w]]
        # m prefers his wife to this woman
        c4 = array(rank_men[m])[wife[m]] < rank_men[m][w]
        constraint(c3 <= c4)

if solve(list(wife) + list(husband)):
    for i in range(n):
        wife_value = wife[i].value()
        assert wife_value is not None
        print(f"{men[i]} <=> {women[wife_value]}")
Example #26
0
import facile

colouring = [facile.variable(range(3)) for i, _ in enumerate(points)]
colours = ["ro", "bo", "go"]

# Build edges between the five nodes in the inner circle
for i in range(5):
    j, j_ = i, (i + 2) % 5  # % (modulo -> j=4, j_=0)
    facile.constraint(colouring[j] != colouring[j_])

# Build edges between the inner and the outer circle
for i in range(5):
    facile.constraint(colouring[i] != colouring[i + 5])

# Build edges between the five nodes on the outer circle
for i in range(5):
    j, j_ = 5 + i, 5 + (i + 1) % 5  # % (modulo -> j=9, j_=5)
    facile.constraint(colouring[j] != colouring[j_])

plot_edges()

if facile.solve(colouring):
    for i, (x_, y_) in enumerate(points):
        plt.plot(x_, y_, colours[colouring[i].value()])
else:
    print("No solution found")
Example #27
0
# -*- coding: utf-8 -*-
"""
Find four numbers such that their sum is 711 and their product is 711000000
"""

from facile import variable, constraint, solve

a = variable(0, 330)
b = variable(0, 160)
c = variable(0, 140)
d = variable(0, 140)

constraint(a + b + c + d == 711)
constraint(a * b * c * d == 711000000)

if solve([a, b, c, d]):
    [va, vb, vc, vd] = [x.value() for x in [a, b, c, d]]
    print("Solution found a=%d, b=%d, c=%d, d=%d" % (va, vb, vc, vd))
else:
    print("No solution found")
Example #28
0
constraint(buckets[0][2] == 0)

constraint(buckets[steps - 1][0] == 4)
constraint(buckets[steps - 1][1] == 4)
constraint(buckets[steps - 1][2] == 0)

for i in range(steps - 1):
    # we change the contents of two buckets at a time
    sum_buckets = sum([buckets[i][b] != buckets[i + 1][b] for b in range(nb)])
    constraint(sum_buckets == 2)
    # we play with a constant amount of water
    sum_water = sum([buckets[i][b] for b in range(nb)])
    constraint(sum_water == 8)
    for b1 in range(nb):
        for b2 in range(b1):
            constraint(
                # either the content of the bucket does not change
                (buckets[i][b1] == buckets[i + 1][b1])
                | (buckets[i][b2] == buckets[i + 1][b2])
                |
                # or the bucket ends up empty or full
                (buckets[i + 1][b1] == 0)
                | (buckets[i + 1][b1] == capacity[b1])
                | (buckets[i + 1][b2] == 0)
                | (buckets[i + 1][b2] == capacity[b2])
            )

if solve([b for sub in buckets for b in sub]):
    for sub in buckets:
        print([b.value() for b in sub])
Example #29
0
    # [1] Use a Sorting Constraint (redundant with [2])
    s = groups[i, :].sort()
    for j in range(nb_golfers):
        facile.constraint(s[j] == j // size_group)

    # [2] Use a Global Cardinality Constraint (redundant with [1])
    gcc = groups[i, :].gcc([(size_group, i) for i in range(nb_groups)])
    facile.constraint(gcc)

# Two golfers do not play in the same group more than once
for g1 in range(nb_golfers):
    for g2 in range(g1 + 1, nb_golfers):
        g1_with_g2 = [groups[w, g1] == groups[w, g2] for w in range(nb_weeks)]
        facile.constraint(facile.sum(g1_with_g2) <= 1)

# Breaking the symmetries
#  - 0 always in the first group, 1 in a group less than 1, ...
#  - First week (0) a priori chosen

for w in range(nb_weeks):
    for g in range(nb_groups):
        facile.constraint(groups[w, g] <= g)

for g in range(nb_golfers):
    facile.constraint(groups[0, g] == g // size_group)

if not facile.solve(list(groups)):
    print("No solution found")
else:
    print(groups.value())
Example #30
0
buckets = [ [variable(0, capacity[b]) for b in range(nb)] for i in range(steps)]

constraint(buckets[0][0] == 8)
constraint(buckets[0][1] == 0)
constraint(buckets[0][2] == 0)

constraint(buckets[steps - 1][0] == 4)
constraint(buckets[steps - 1][1] == 4)
constraint(buckets[steps - 1][2] == 0)

for i in range(steps - 1):
    # we change the contents of two buckets at a time
    constraint( sum([buckets[i][b] != buckets[i+1][b] for b in range(nb)]) == 2)
    # we play with a constant amount of water
    constraint(sum([buckets[i][b] for b in range(nb)]) == 8)
    for b1 in range(nb):
        for b2 in range(b1):
            constraint(
                # either the content of the bucket does not change
                (buckets[i][b1] == buckets[i+1][b1]) |
                (buckets[i][b2] == buckets[i+1][b2]) |
                # or the bucket ends up empty or full
                (buckets[i+1][b1] == 0) | (buckets[i+1][b1] == capacity[b1]) |
                (buckets[i+1][b2] == 0) | (buckets[i+1][b2] == capacity[b2])
                )

if solve([b for sub in buckets for b in sub]):
    for sub in buckets:
        print ([b.value() for b in sub])
Example #31
0
old_gold, kools, chesterfields, lucky_strike, parliaments = cigarettes

constraint(alldifferent(colors))
constraint(alldifferent(people))
constraint(alldifferent(animals))
constraint(alldifferent(drinks))
constraint(alldifferent(cigarettes))

constraint(englishman == red)
constraint(spaniard == dog)
constraint(coffee == green)
constraint(ukrainian == tea)
constraint(green == ivory + 1)
constraint(old_gold == snails)
constraint(kools == yellow)
constraint(milk == 3)
constraint(norwegian == 1)
constraint(abs(fox - chesterfields) == 1)
constraint(abs(horse - kools) == 1)
constraint(lucky_strike == fruit_juice)
constraint(japanese == parliaments)
constraint(abs(norwegian - blue) == 1)

assert solve(colors + people + animals + drinks + cigarettes)

water_drinker = [n for n, p in zip(names, people) if p.value() == water.value()]
zebra_owner = [n for n, p in zip(names, people) if p.value() == zebra.value()]

print("The {} drinks water.".format(water_drinker[0]))
print("The {} owns the zebra.".format(zebra_owner[0]))
Example #32
0
# -*- coding: utf-8 -*-
"""
Basic examples of CSP problems:
    - a ≠ b
    - alldifferent(a, b, c) and a + b <= 2c
"""

from facile import variable, constraint, solve, alldifferent

a = variable(0, 1)
b = variable(0, 1)

constraint(a != b)

if solve([a, b]):
    print("Solution found a=%d and b=%d" % (a.value(), b.value()))

a = variable(0, 2)
b = variable(0, 2)
c = variable(0, 2)

constraint(alldifferent([a, b, c]))
constraint(a + b <= 2 * c)
if solve([a, b, c]):
    print("Solution found a=%d, b=%d and c=%d" %
          (a.value(), b.value(), c.value()))
Example #33
0
    s = groups[i].sort()
    for j in range(nb_golfers):
        facile.constraint(s[j] == j // size_group)

    # [2] Use a Global Cardinality Constraint (redundant with [1])
    gcc = groups[i].gcc([(size_group, i) for i in range(nb_groups)])
    facile.constraint(gcc)

# Two golfers do not play in the same group more than once
for g1 in range(nb_golfers):
    for g2 in range(g1 + 1, nb_golfers):
        g1_with_g2 = [groups[w][g1] == groups[w][g2] for w in range(nb_weeks)]
        facile.constraint(sum(g1_with_g2) <= 1)

# Breaking the symmetries
#  - 0 always in the first group, 1 in a group less than 1, ...
#  - First week (0) a priori chosen

for w in range(nb_weeks):
    for g in range(nb_groups):
        facile.constraint(groups[w][g] <= g)

for g in range(nb_golfers):
    facile.constraint(groups[0][g] == g // size_group)

if (not facile.solve([v for k in groups for v in k])):
    print("No solution found")
else:
    for v in groups:
        print(v.value())
Example #34
0
import facile

# Magical sequence!
# The value inside array[i] is equal to the number of i in array

array = [facile.variable(0, 10) for i in range(10)]

for i in range(10):
    facile.constraint(sum([x == i for x in array]) == array[i])

if facile.solve(array):
    print([v.value() for v in array])
Example #35
0
# -*- coding: utf-8 -*-

"""
Find four numbers such that their sum is 711 and their product is 711000000
"""

from facile import variable, constraint, solve

a = variable(0, 330)
b = variable(0, 160)
c = variable(0, 140)
d = variable(0, 140)

constraint(a + b + c + d == 711)
constraint(a * b * c * d == 711000000)

if solve([a, b, c, d]):
    [va, vb, vc, vd] = [x.value() for x in [a, b, c, d]]
    print ("Solution found a=%d, b=%d, c=%d, d=%d" % (va, vb, vc, vd))
else:
    print ("No solution found")
Example #36
0
import facile
import functools

# The list comprehension mechanism is always helpful!
[s, e, n, d, m, o, r, y] = [facile.variable(range(10)) for i in range(8)]

# A shortcut
letters = [s, e, n, d, m, o, r, y]

# Constraints
facile.constraint(s > 0)
facile.constraint(m > 0)
facile.constraint(facile.alldifferent(letters))

send = functools.reduce(lambda x, y: 10 * x + y, [s, e, n, d])
more = functools.reduce(lambda x, y: 10 * x + y, [m, o, r, e])
money = functools.reduce(lambda x, y: 10 * x + y, [m, o, n, e, y])

facile.constraint(send + more == money)

if facile.solve(letters):
    [vs, ve, vn, vd, vm, vo, vr, vy] = [x.value() for x in letters]
    print("Solution found :")
    print
    print("  %d%d%d%d" % (vs, ve, vn, vd))
    print("+ %d%d%d%d" % (vm, vo, vr, ve))
    print("------")
    print(" %d%d%d%d%d" % (vm, vo, vn, ve, vy))
else:
    print("No solution found")
Example #37
0
facile.constraint(buckets[0][0] == 8)
facile.constraint(buckets[0][1] == 0)
facile.constraint(buckets[0][2] == 0)

facile.constraint(buckets[steps - 1][0] == 4)
facile.constraint(buckets[steps - 1][1] == 4)
facile.constraint(buckets[steps - 1][2] == 0)

for i in range(steps - 1):
    # we change the contents of two buckets at a time
    facile.constraint(
        sum([buckets[i][b] != buckets[i + 1][b] for b in range(nb)]) == 2)
    # we play with a constant amount of water
    facile.constraint(sum([buckets[i][b] for b in range(nb)]) == 8)
    for b1 in range(nb):
        for b2 in range(b1):
            facile.constraint(
                # either the content of the bucket does not change
                (buckets[i][b1] == buckets[i + 1][b1])
                | (buckets[i][b2] == buckets[i + 1][b2])
                |
                # or the bucket ends up empty or full
                (buckets[i + 1][b1] == 0)
                | (buckets[i + 1][b1] == capacity[b1])
                | (buckets[i + 1][b2] == 0)
                | (buckets[i + 1][b2] == capacity[b2]))

print(facile.solve([b for sub in buckets for b in sub], backtrack=True))
for sub in buckets:
    print([b.value() for b in sub])