Solve triangle solitaire puzzle: Difference between revisions

Content added Content deleted
(Updated task)
(→‎{{header|Ruby}}: change of the termination condition)
Line 973: Line 973:


<lang ruby># Solitaire Like Puzzle Solver - Nigel Galloway: October 18th., 2014
<lang ruby># Solitaire Like Puzzle Solver - Nigel Galloway: October 18th., 2014
PEGS = (N = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1]).inject(:+)
pegs = (N = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1]).inject(:+)
G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9],[3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12],[5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14]]
G = [[0,1,3],[0,2,5],[1,3,6],[1,4,8],[2,4,7],[2,5,9],[3,4,5],[3,6,10],[3,7,12],[4,7,11],[4,8,13],[5,8,12],[5,9,14],[6,7,8],[7,8,9],[10,11,12],[11,12,13],[12,13,14]]
FORMAT = (1..5).map{|i| " "*(5-i)+"%d "*i+"\n"}.join+"\n"
FORMAT = (1..5).map{|i| " "*(5-i)+"%d "*i+"\n"}.join+"\n"
def solve n,i,g
def solve n,i,g
return "Solved" if i == PEGS
return "Solved" if i == 1
return false unless n[g[1]]==1
return false unless n[g[1]]==1
if n[g[0]] == 0
if n[g[0]] == 0
return false unless n[g[2]]==1
return false unless n[g[2]]==1
s = "#{g[2]} to #{g[0]}\n"
s = "#{g[2]} to #{g[0]}\n"
else
else
return false unless n[g[2]]==0
return false unless n[g[2]]==0
Line 987: Line 987:
end
end
a = n.clone; g.each{|n| a[n] = 1 - a[n]}
a = n.clone; g.each{|n| a[n] = 1 - a[n]}
l=false; G.each{|g| l=solve(a,i+1,g); break if l}
l=false; G.each{|g| l=solve(a,i-1,g); break if l}
return l ? s + FORMAT % a + l : l
return l ? s + FORMAT % a + l : l
end
end
puts FORMAT % N
puts FORMAT % N
l=false; G.each{|g| l=solve(N,1,g); break if l}
l=false; G.each{|g| l=solve(N,pegs,g); break if l}
puts l ? l : "No solution found"
puts l ? l : "No solution found"</lang>
</lang>
{{out}}
{{out}}
<pre style="height:64ex;overflow:scroll">
<pre style="height:64ex;overflow:scroll">