diff --git a/ruby/2015/3/bin/problem b/ruby/2015/3/bin/problem new file mode 100644 index 0000000..2b6d07b --- /dev/null +++ b/ruby/2015/3/bin/problem @@ -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}" \ No newline at end of file diff --git a/ruby/2015/3/lib/santa.rb b/ruby/2015/3/lib/santa.rb new file mode 100644 index 0000000..5d0d923 --- /dev/null +++ b/ruby/2015/3/lib/santa.rb @@ -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