2015/3/script.rb

99 lines
1.7 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require_relative '../common'
class Grid
def initialize(robosanta: false)
@robosanta = robosanta
@santa_position = Position.new
@robosanta_position = Position.new
@grid = Hash.new(0)
give_from_santa
give_from_robosanta
end
def houses_count
@grid.size
end
def move_santa(direction)
@santa_position.move direction
give_from_santa
end
def move_robosanta(direction)
@robosanta_position.move direction
give_from_robosanta
end
def give_from_santa
@grid[@santa_position.position] += 1
end
def give_from_robosanta
return unless @robosanta
@grid[@robosanta_position.position] += 1
end
end
class Position
attr_accessor :position
def initialize
self.position = [0, 0]
end
def move(direction)
case direction
when '^'
up
when 'v'
down
when '<'
left
when '>'
right
end
end
def up
self.position = [position[0] - 1, position[1]]
end
def down
self.position = [position[0] + 1, position[1]]
end
def left
self.position = [position[0], position[1] - 1]
end
def right
self.position = [position[0], position[1] + 1]
end
end
def part1
Input.new(__dir__).readlines.join.chars.each_with_object(Grid.new) do |direction, grid|
grid.move_santa direction
end.houses_count
end
def part2(input)
input.chars.each_with_object(Grid.new(robosanta: true)).with_index do |(direction, grid), i|
if i.even?
grid.move_santa direction
else
grid.move_robosanta direction
end
end.houses_count
end
puts "=== Part 1 ==="
puts part1
puts "=== Part 2 ==="
puts part2(Input.new(__dir__).readlines.join)