2015 day 3 ruby
This commit is contained in:
parent
7c063782df
commit
a102279609
12
ruby/2015/3/bin/problem
Normal file
12
ruby/2015/3/bin/problem
Normal file
@ -0,0 +1,12 @@
|
||||
#/usr/bin/env ruby
|
||||
|
||||
require "santa"
|
||||
|
||||
directions = STDIN.read.chomp
|
||||
santa = Santa.for(directions)
|
||||
santa.run!
|
||||
puts "Part 1: #{santa.visited_houses.length}"
|
||||
|
||||
squad = Santa::Squad.for(directions, 2)
|
||||
squad.run!
|
||||
puts "Part 2: #{squad.visited_houses.length}"
|
||||
57
ruby/2015/3/lib/santa.rb
Normal file
57
ruby/2015/3/lib/santa.rb
Normal file
@ -0,0 +1,57 @@
|
||||
require "set"
|
||||
|
||||
class Santa
|
||||
attr_reader :visited_houses, :directions, :x, :y
|
||||
|
||||
def initialize(directions, vh=Set.new)
|
||||
@directions = directions
|
||||
@visited_houses = vh
|
||||
@x = 0
|
||||
@y = 0
|
||||
end
|
||||
|
||||
def self.for(string)
|
||||
new string.split("")
|
||||
end
|
||||
|
||||
def handle_direction!(direction)
|
||||
case direction
|
||||
when "^"
|
||||
@y -= 1
|
||||
when "v"
|
||||
@y += 1
|
||||
when "<"
|
||||
@x -= 1
|
||||
when ">"
|
||||
@x += 1
|
||||
end
|
||||
@visited_houses.add [x, y]
|
||||
end
|
||||
|
||||
def run!
|
||||
@visited_houses.add [x, y]
|
||||
|
||||
directions.each do |direction|
|
||||
handle_direction! direction
|
||||
end
|
||||
end
|
||||
|
||||
class Squad
|
||||
attr_reader :directions, :santas, :visited_houses
|
||||
def initialize(directions, count)
|
||||
@directions = directions
|
||||
@visited_houses = Set.new
|
||||
@santas = 1.upto(count).map { Santa.new nil, @visited_houses }
|
||||
end
|
||||
|
||||
def self.for(string, count)
|
||||
new string.split(""), count
|
||||
end
|
||||
|
||||
def run!
|
||||
directions.each_with_index do |direction, index|
|
||||
santas[index % 2].handle_direction! direction
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Reference in New Issue
Block a user