Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Last active December 11, 2015 04:18
Show Gist options
  • Select an option

  • Save practicingruby/4543956 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/4543956 to your computer and use it in GitHub Desktop.
Puzzlenode #4 in Lua
-- Implements the Robots vs. Lasers problem:
-- http://puzzlenode.com/puzzles/4-robots-vs-lasers
conveyors = {}
function conveyors.parse(filename)
local f = io.open(filename, "r")
local conveyors = {}
repeat
local top, middle, bottom = f:read("*line", "*line", "*line")
local north_lasers = {}
local south_lasers = {}
for c in top:gmatch(".") do
table.insert(north_lasers, c == "|")
end
for c in bottom:gmatch(".") do
table.insert(south_lasers, c == "|")
end
table.insert(conveyors, { north_lasers = north_lasers,
south_lasers = south_lasers,
robot_position = middle:find("X") })
until f:read("*line") == nil
io.close(f)
return conveyors
end
function conveyors.compute_danger(conveyor, destination)
local direction = destination > conveyor.robot_position and 1 or -1
local score, clicks = 0, 0
for i=conveyor.robot_position, destination, direction do
if clicks % 2 == 0 and conveyor.north_lasers[i] then
score = score + 1
elseif clicks % 2 == 1 and conveyor.south_lasers[i] then
score = score + 1
end
clicks = clicks + 1
end
return score
end
function conveyors.optimize(filename)
for i,c in ipairs(conveyors.parse(filename)) do
local east_score = conveyors.compute_danger(c, #c.north_lasers)
local west_score = conveyors.compute_danger(c, 1)
if east_score < west_score then
print "GO EAST"
else
print "GO WEST"
end
end
end
conveyors.optimize(arg[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment