水差しの問題を解決するために IA 幅優先検索のようなアルゴリズムを実装しようとしていますが、次の問題が発生しました。
配列に新しい要素を追加するたびに、配列内のすべての要素がそのように変更されます。
言い換えると...
「フロンティア」配列は、「ジャグ」関数呼び出しごとにその中のすべての要素を変更しています。
誰かがこのコードについての洞察を共有できますか?
(ロジックの実装の方が心配だったので、最適化されていません)
コード:
J1SIZE = 3
J2SIZE = 4
frontier = []
explored = []
def IsEmpty(array):
result = False
if len(array) == 0:
result = True
return result
#Fill up a jug
def fillJug(tempNode, jug):
copyNode = tempNode
copyNode = copyNode
if jug == 1:
copyNode[0] = J1SIZE
elif jug == 2:
copyNode[1] = J2SIZE
print(copyNode)
return copyNode
#Empty a jug
def emptyJug(tempNode, jug):
copyNode = tempNode
if jug == 1:
copyNode[0] = 0
elif jug == 2:
copyNode[1] = 0
print(copyNode)
return copyNode
#Pass the content of a jug to another
def passJug(tempNode, jug):
copyNode = tempNode
if jug == 1:
copyNode[1] = copyNode.j1
copyNode[0] = 0
if copyNode[1] > J2SIZE:
copyNode[1] = J2SIZE
elif jug == 2:
copyNode[0] = copyNode[1]
copyNode[1] = 0
if copyNode[0] > J1SIZE:
copyNode[0] = J1SIZE
print(copyNode)
return copyNode
#Check if solution was found
def goalTest(goalNode,currentNode):
result = False
if goalNode == currentNode:
result = True
return result
def BFS(start,end,frontier,explored):
start_node = start
frontier = [start_node] + frontier
if goalTest(end,(frontier[0])):
print('Solution:', frontier[0])
exit()
#Loop start
while IsEmpty(frontier) == False:
tempNode = frontier.pop(0)
#Generate nodes (states)
if tempNode[0] < J1SIZE:
newNode = fillJug(tempNode, 1)
if newNode not in explored:
frontier = [newNode] + frontier
print('Frontier1: ', frontier)
if tempNode[1] < J2SIZE:
newNode = fillJug(tempNode, 2)
if newNode not in explored:
frontier = [newNode] + frontier
print('Frontier2: ', frontier)
if tempNode[0] == J1SIZE:
newNode = emptyJug(tempNode, 1)
if newNode not in explored:
frontier = [newNode] + frontier
print('Frontier3: ', frontier)
if tempNode[1] == J2SIZE:
newNode = emptyJug(tempNode, 2)
if newNode not in explored:
frontier = [newNode] + frontier
print('Frontier4: ', frontier)
if (tempNode[0] > 0) and (tempNode[1] < J2SIZE):
newNode = passJug(tempNode, 1)
if newNode not in explored:
frontier = [newNode] + frontier
print('Frontier5: ', frontier)
if (tempNode[1] > 0) and (tempNode[0] < J1SIZE):
new_node = passJug(tempNode, 2)
if new_node not in explored:
frontier = [new_node] + frontier
print('Frontier6: ', frontier)
print('Frontier: ', frontier)
print('Explored: ', explored)
for node in frontier:
if goalTest(end, node):
print('Solution:', frontier[0])
exit()
if node not in explored:
explored = [node] + explored
BFS([0,0],[0,2],frontier,explored)
固定コード: