Skip to content

Instantly share code, notes, and snippets.

@JackBracken
Created December 2, 2016 10:58
Show Gist options
  • Save JackBracken/20778f794247ddacab2a19fb33f58aa8 to your computer and use it in GitHub Desktop.
Save JackBracken/20778f794247ddacab2a19fb33f58aa8 to your computer and use it in GitHub Desktop.
Advent of code 2016, 1a.
#!/usr/bin/env ruby
# The naive approach
input = "R5, R4, R2, L3, R1, R1, L4, L5, R3, L1, L1, R4, L2, R1, R4, R4, L2, L2, R4, L4, R1, R3, L3, L1, L2, R1, R5, L5, L1, L1, R3, R5, L1, R4, L5, R5, R1, L185, R4, L1, R51, R3, L2, R78, R1, L4, R188, R1, L5, R5, R2, R3, L5, R3, R4, L1, R2, R2, L4, L4, L5, R5, R4, L4, R2, L5, R2, L1, L4, R4, L4, R2, L3, L4, R2, L3, R3, R2, L2, L3, R4, R3, R1, L4, L2, L5, R4, R4, L1, R1, L5, L1, R3, R1, L2, R1, R1, R3, L4, L1, L3, R2, R4, R2, L2, R1, L5, R3, L3, R3, L1, R4, L3, L3, R4, L2, L1, L3, R2, R3, L2, L1, R4, L3, L5, L2, L4, R1, L4, L4, R3, R5, L4, L1, L1, R4, L2, R5, R1, R1, R2, R1, R5, L1, L3, L5, R2".split(', ')
dist = hor = ver = 0
facing = :north
def turn(facing, dir)
if dir == :right
case facing
when :north
facing = :east
when :east
facing = :south
when :south
facing = :west
when :west
facing = :north
end
else
case facing
when :north
facing = :west
when :east
facing = :north
when :south
facing = :east
when :west
facing = :south
end
end
return facing
end
input.each do |mv|
# Which way do we turn?
mv[0] == 'R' ? dir = :right : dir = :left
# How far do we go?
mov = mv[1..-1].to_i
# Turn!
facing = turn(facing, dir)
# Walk!
case facing
when :north
ver = ver + mov
when :east
hor = hor + mov
when :south
ver = ver - mov
when :west
hor = hor - mov
else
puts "You dun fucking goofed."
end
end
puts "Vertical distance: #{ver}"
puts "Horizontal distance: #{hor}"
puts "Total distance moved: #{hor.abs + ver.abs}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment