Last active
July 31, 2016 02:32
-
-
Save petertseng/6d0c15ba7970bb80ab5c8485b82046f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FlowerPuzzle | |
refine Array do | |
def to_i | |
reduce(0) { |acc, e| acc * 3 + e } | |
end | |
def apply_move(move) | |
zip(move).map { |a, b| (a + b) % 3 } | |
end | |
end | |
end | |
INITIAL_STATE = [ | |
0, 0, 0, 0, | |
0, 2, 2, 0, | |
0, 0, 0, 0, | |
].freeze | |
MOVES = [ | |
[ | |
2, 1, 0, 0, | |
1, 0, 0, 0, | |
0, 0, 0, 0, | |
], | |
[ | |
1, 2, 1, 0, | |
0, 1, 0, 0, | |
0, 0, 0, 0, | |
], | |
[ | |
0, 1, 2, 1, | |
0, 0, 1, 0, | |
0, 0, 0, 0, | |
], | |
[ | |
0, 0, 1, 2, | |
0, 0, 0, 1, | |
0, 0, 0, 0, | |
], | |
[ | |
1, 0, 0, 0, | |
2, 1, 0, 0, | |
1, 0, 0, 0, | |
], | |
[ | |
0, 1, 0, 0, | |
1, 2, 1, 0, | |
0, 1, 0, 0, | |
], | |
[ | |
0, 0, 1, 0, | |
0, 1, 2, 1, | |
0, 0, 1, 0, | |
], | |
[ | |
0, 0, 0, 1, | |
0, 0, 1, 2, | |
0, 0, 0, 1, | |
], | |
[ | |
0, 0, 0, 0, | |
1, 0, 0, 0, | |
2, 1, 0, 0, | |
], | |
[ | |
0, 0, 0, 0, | |
0, 1, 0, 0, | |
1, 2, 1, 0, | |
], | |
[ | |
0, 0, 0, 0, | |
0, 0, 1, 0, | |
0, 1, 2, 1, | |
], | |
[ | |
0, 0, 0, 0, | |
0, 0, 0, 1, | |
0, 0, 1, 2, | |
], | |
].freeze | |
MOVES.each(&:freeze) | |
using FlowerPuzzle | |
def search(initial_state) | |
frontier = [[initial_state, []]] | |
seen = {} | |
until frontier.empty? | |
state, moves = frontier.shift | |
seen[state.to_i] = true | |
MOVES.each_with_index { |move, i| | |
new_state = state.apply_move(move) | |
next if seen[new_state.to_i] | |
new_moves = moves + [i] | |
return new_moves.freeze if new_state.all? { |x| x == 2 } | |
frontier << [new_state, new_moves] | |
} | |
end | |
end | |
best_moves = search(INITIAL_STATE) | |
state = INITIAL_STATE | |
best_moves.each { |move| | |
state = state.apply_move(MOVES[move]) | |
puts "Move #{move}" | |
state.each_slice(4) { |row| puts row.to_s } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Move 0 | |
[2, 1, 0, 0] | |
[1, 2, 2, 0] | |
[0, 0, 0, 0] | |
Move 2 | |
[2, 2, 2, 1] | |
[1, 2, 0, 0] | |
[0, 0, 0, 0] | |
Move 7 | |
[2, 2, 2, 2] | |
[1, 2, 1, 2] | |
[0, 0, 0, 1] | |
Move 8 | |
[2, 2, 2, 2] | |
[2, 2, 1, 2] | |
[2, 1, 0, 1] | |
Move 10 | |
[2, 2, 2, 2] | |
[2, 2, 2, 2] | |
[2, 2, 2, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment