我正在尝试使用Depth First Search来弄清楚如何制作Water Bucket问题解决方案。 我遇到问题,我不知何故得到无法退出的状态。 现在只实现进程FILL和EMPTY
Example:
2 jugs, 3l, 4l, I need 4
input :> 2,3,4,4
Output :> inf. loop of [[3,3],[3.3]]
我正在使用Node Class
class Node
attr_reader :parent, :state, :childrens
def initialize(parent, state, childrens)
@parent = parent
@state = state
@childrens = childrens
end
end
应该实现DFS的主类
require_relative 'node'
$solutions = Array.new
def DFS(node, bag, target)
puts "Starting Function"
node.state.each do |s|
s.size.times do |b|
=begin
FILL FUNCTION
=end
# Loome uue seisu
n_state = Marshal.load(Marshal.dump(s))
n_state[b][1] = n_state[b][0]
n_state = [n_state]
# Kontrollime, kas on juba olnud
if bag.has_key?(n_state)
return bag
end
# Kontrollime, kas on lahendus
solution = n_state.select{|k| k.any?{|v| v[1] == target}}[0]
if solution
$solutions.push(n_state)
return bag
end
bag[node.state] = n_state.to_s + " FILL "
child = Node.new(node, n_state, nil)
puts child.state.to_s + " : " + bag.to_s
bag = DFS(child, bag, target)
=begin
EMPTY FUNCTION
=end
# Loome uue seisu
kann = Marshal.load(Marshal.dump(s))
kann[b][1] = 0
n_state = [n_state]
# Kontrollime, kas on juba olnud
if bag.has_key?(n_state)
return bag
end
# Kontrollime, kas on lahendus
solution = n_state.select{|k| k.any?{|v| v[1] == target}}[0]
if solution
$solutions.push(n_state)
return bag
end
bag[node.state] = n_state.to_s + " Empty "
child = Node.new(node, n_state, nil)
puts child.state.to_s + " : " + bag.to_s
DFS(child, bag, target)
end
end
end
=begin
Sisendi Muster järgimne :
"a , a * [x] , d" ,
kus a on veekannude arv,
a*[x] on veekannued mahud
ja d on soovitud lõpptulemus
Näide:
2 , 3 , 4 , 2
Mul on 2 veekannu 3l ja 4l. Tulemuseks tahan saada 2l.
=end
# Küsime sisendi
input = gets.split(/,/).map{|p| p.to_i} # Saame sisendi lõigume tükkideks "," järgi ja muudame kõik osad intideks (to_int)
# Määrame ära keskkonna.
count = input.shift # saame koguse
start = (1..count).map{[input.shift, 0]} # saame iga veekannu mahu
target= input.shift # viimane element on meie soovitud tulemus
step = 0
states = {start => ""} # Hashmap, kus start on võti ja "" väärtus.
current = states.keys
start_node = Node.new(nil, current, nil)
states = {start => ""}
puts "GIVING STATE : " + current.to_s
DFS(start_node, states, target)
puts "SOLUTIONS FOUND :"
puts $solutions.to_s
答案 0 :(得分:0)