Last active
August 29, 2015 14:04
-
-
Save sdsykes/d5c8895476c0f76c3ac8 to your computer and use it in GitHub Desktop.
A quick and dirty solver for Inverter http://gorried.github.io/inverter/game.html
This file contains hidden or 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
$size = ARGV[0].to_i | |
if $size <= 0 | |
puts "Supply numeric level (grid size) as an argument" | |
exit | |
end | |
def show(placement) | |
0.upto($size - 1) do |x| | |
0.upto($size - 1) do |y| | |
if placement.include?([x, y]) | |
print "[*]" | |
else | |
print "[ ]" | |
end | |
end | |
puts | |
end | |
end | |
$placings = [] | |
0.upto($size - 1) do |x| | |
$placings[x] = [] | |
0.upto($size - 1) do |y| | |
$placings[x][y] = (1 << (y * $size + x)) + | |
(y > 0 ? (1 << ((y - 1) * $size + x)) : 0) + | |
(x > 0 ? (1 << (y * $size + x - 1)) : 0) + | |
(x < $size - 1 ? (1 << (y * $size + x + 1)) : 0) + | |
(y < $size - 1 ? (1 << ((y + 1) * $size + x)) : 0) | |
end | |
end | |
$solution = (1 << $size * $size) - 1 | |
def check(startindex, bits, cur_placings) | |
x = startindex % $size | |
y = startindex / $size | |
v = $placings[x][y] | |
new_bits = bits ^ v | |
if new_bits == $solution | |
return [cur_placings + [[x,y]], true] | |
end | |
return [cur_placings, false] if startindex == $size * $size - 1 | |
above_bit = (y == 0 ? 0 : (1 << (y - 1) * $size + x)) | |
if y == 0 || bits & above_bit > 0 | |
(placement, solved) = check(startindex + 1, bits, cur_placings) | |
return [placement, true] if solved | |
end | |
if y == 0 || bits & above_bit == 0 | |
(placement, solved) = check(startindex + 1, bits ^ v, cur_placings + [[x,y]]) | |
return [placement, true] if solved | |
end | |
return [placement, false] | |
end | |
(placement, solved) = check(0, 0, []) | |
if solved | |
show(placement) | |
else | |
puts "No solution" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved. It will solve up to level seventeen under 10 secs on my machine. Algorithm is still O(2^n) though.