簡體   English   中英

如何使用 python-constraint 將此約束添加到問題中

[英]How to add this constraint to a problem using python-constraint

我正在嘗試使用 python-constraint 來解決組合問題,但我似乎無法將我需要的約束添加到問題中。 我的問題是我有 9 個方形瓷磚必須放置,每個瓷磚都可以旋轉到 4 個位置之一,我已經將這些瓷磚編碼為矢量並且需要特定的元素對來添加到零。

使用帶有兩個圖塊的示例:

piece_1 = np.array([-1,-3, 4, 2])

piece_2 = np.array([-2, -1, 3, 2])

每個向量都可以滾動形成一組 4 個向量:

piece_1_set = [np.roll(piece_1, i) for i in range(4)]

piece_2_set = [np.roll(piece_2, i) for i in range(4)]

我已經將它們添加到問題中:

problem.addVariable("1", piece_1_set)

problem.addVariable("2", piece_2_set)

我想要做的是從每個集合中找到一個向量,使得第一個向量中的第二個元素和第二個向量中的第四個元素總和為 0。

我嘗試了各種版本:

problem.addConstraint(lambda i,j: i[1] + j[3] == 0, ("1", "2"))

problem.addConstraint(lambda i,j: np.any(i[1]) + np.any(j[3]) == 0, ("1", "2"))

但我總是返回以下內容:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有誰知道如何表達這個約束,以便我可以添加它們來獲得問題的解決方案?

問題似乎只是您正在嘗試將 numpy arrays 與 python-constraint 庫一起使用,而不是內置的 python 列表。 您需要按照下面的解決方案將它們轉換回來。

import numpy as np
from constraint import *

problem = Problem()

piece_1 = np.array([-1,-3, 4, 2])
piece_2 = np.array([-2, -1, 3, 2])
piece_1_set = [list(np.roll(piece_1, i)) for i in range(4)]
piece_2_set = [list(np.roll(piece_2, i)) for i in range(4)]

problem.addVariable("1", piece_1_set)
problem.addVariable("2", piece_2_set)

problem.addConstraint(lambda i, j: i[0] == j[0], ("1", "2"))
problem.getSolutions()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM