Advertisement
Guest User

Untitled

a guest
Dec 12th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.01 KB | None | 0 0
  1. INSTRUCTIONS = File.readlines("day12_input.txt").map { |line| [line[0], line.chomp[1..].to_i] }
  2.  
  3. def move_ship(ship, instructions, mover)
  4.   i = Complex::I
  5.  
  6.   instructions.each do |instr|
  7.     case instr[0]
  8.     when /[ENWS]/
  9.       wp_add = case instr[0]
  10.       when 'E'
  11.         instr[1]
  12.       when 'N'
  13.         instr[1]*i
  14.       when 'W'
  15.         -instr[1]
  16.       when 'S'
  17.         -instr[1]*i
  18.       end
  19.    
  20.       ship[mover] += wp_add
  21.     when 'F'
  22.       ship[:pos] += ship[:wp] * instr[1]
  23.     when /[LR]/
  24.       sign = instr[0] == 'L' ? 1 : -1
  25.       degrees = (sign * instr[1]) % 360
  26.       wp_dir = Complex::polar(1, Math::PI * degrees / 180)
  27.    
  28.       ship[:wp] *= wp_dir
  29.     end
  30.   end
  31. end
  32.  
  33. # Part 1
  34. ship1 = { pos: Complex(0, 0), wp: Complex(1, 0) }
  35. move_ship(ship1, INSTRUCTIONS, :pos)
  36. puts "#{ ship1[:pos].real.abs + ship1[:pos].imag.abs }"
  37.  
  38. # Part 2
  39. ship2 = { pos: Complex(0, 0), wp: Complex(10, 1) }
  40. move_ship(ship2, INSTRUCTIONS, :wp)
  41. puts "#{ ship2[:pos].real.abs + ship2[:pos].imag.abs }"
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement