Advertisement
RobOEM

Advent of code 2016 day 1

Dec 1st, 2016
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.07 KB | None | 0 0
  1. @posx=0
  2. @posy=0
  3. orient="N"
  4. step=0
  5. part2=0
  6. #    N
  7. #  W   E
  8. #    S
  9. move={
  10.    "N"=>lambda {|num|@posy=@posy+num},
  11.    "S"=>lambda {|num|@posy=@posy-num},
  12.    "E"=>lambda {|num|@posx=@posx+num},
  13.    "W"=>lambda {|num|@posx=@posx-num}
  14.    }
  15. orientation={
  16.   "N"=>{"R"=>"E","L"=>"W"},
  17.   "S"=>{"R"=>"W","L"=>"E"},
  18.   "E"=>{"R"=>"S","L"=>"N"},
  19.   "W"=>{"R"=>"N","L"=>"S"}
  20. }
  21. visited=Hash.new
  22. File.read("day1.input").split(', ').each {|direction|
  23.     orient = orientation[orient][direction[0]]
  24.     oldx,oldy=@posx,@posy
  25.     move[orient].call(direction[1..-1].to_i)
  26.     #Retracing steps
  27.     ([oldx,@posx].min..[oldx,@posx].max).each {|x|
  28.         ([oldy,@posy].min..[oldy,@posy].max).each {|y|
  29.             if visited[x.to_s+','+y.to_s] and visited[x.to_s+','+y.to_s]<step-1 and part2==0
  30.                 puts "Hey, I was already there at step "+visited[x.to_s+','+y.to_s].to_s
  31.                 part2=(x.abs+y.abs)
  32.                 puts "That's "+part2.to_s+" blocks from where I started"
  33.             else
  34.                 visited[x.to_s+','+y.to_s]=step
  35.             end
  36.         }
  37.     }
  38.     step=step+1
  39. }
  40. puts "I am now "+ (@posx.abs+@posy.abs).to_s+" blocks from where I started"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement