Skip to content

Instantly share code, notes, and snippets.

@sdsykes
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdsykes/d5c8895476c0f76c3ac8 to your computer and use it in GitHub Desktop.
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
$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
@sdsykes
Copy link
Author

sdsykes commented Jul 25, 2014

This brute force approach works pretty well up to level 11. At level 12+ more optimisation (or a better algorithm) is required to find a solution in reasonable time. (Takes 10 mins to solve level 12 on my machine)

See also https://news.ycombinator.com/item?id=8038003

@sdsykes
Copy link
Author

sdsykes commented Jul 25, 2014

Improved. It will solve up to level seventeen under 10 secs on my machine. Algorithm is still O(2^n) though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment