[英]How to solve for unknowns in a 5x5 matrix in python
這是一個 5x5 矩陣,所有單元格都未知,它看起來像這樣:
A1+B1+C1+D1+E1| 1
A2+B2+C2+D2+E2| 0
A3+B3+C3+D3+E3| 1
A4+B4+C4+D4+E4| 3
A5+B5+C5+D5+E5| 2
_______________
2 1 2 1 1
因此,可以在右側看到行的總和,在底部可以看到列的總和。 解決方案只能是 0 或 1,作為一個例子,這里是我在上面輸入的特定解決方案的解決方案:
0+0+1+0+0| 1
0+0+0+0+0| 0
1+0+0+0+0| 1
1+1+0+0+1| 3
0+0+1+1+0| 2
____________
2 1 2 1 1
如您所見,對行和列求和得出右側和底部的結果。 我的問題:您將如何使用未知數輸入原始矩陣並讓 python 用 0 或 1 迭代每個單元格,直到拼圖完成?
您實際上並不需要矩陣——只需使用長度為 25 的向量(元組)。它們可以根據以下方案表示 5x5 矩陣:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
這些是這些元組的索引。 請注意,可以從函數divmod
獲得索引的行和列。
您可以使用itertools
product
來迭代 2**25 種可能的矩陣填充方式。
這些想法導致了以下代碼:
from itertools import product
#nxn matrices will be represented by tuples of length n**2,
#in row-major order
#the following function caluculates row and column sums:
def all_sums(array,n):
row_sums = [0]*n
col_sums = [0]*n
for i,x in enumerate(array):
q,r = divmod(i,n)
row_sums[q] += x
col_sums[r] += x
return row_sums, col_sums
#in what follows, row_sums, col_sums are lists of target values
def solve_puzzle(row_sums, col_sums):
n = len(row_sums)
for p in product(range(2),repeat = n*n):
if all_sums(p,n) == (row_sums, col_sums):
return p
return "no solution"
solution = solve_puzzle([1,0,1,3,2],[2,1,2,1,1])
for i in range(0,25,5):
print(solution[i:i+5])
輸出:
(0, 0, 0, 0, 1)
(0, 0, 0, 0, 0)
(0, 0, 0, 1, 0)
(1, 1, 1, 0, 0)
(1, 0, 1, 0, 0)
在這種情況下,蠻力是可行的。 如果遠遠超過 5x5,它將不再可行,並且需要更復雜的算法。
這是 整數線性規划問題的一個特例。 不幸的是,0-1 整數線性規划的特殊情況仍然是 NP 完全的,盡管存在許多算法,包括啟發式算法。 您可以使用內置庫為您執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.