Here is my Day 3 in Ruby
require 'benchmark' class TreeGrid def self.from(file) rows = File.readlines(file) TreeGrid.new(rows) end def initialize(rows) self.rows = rows self.width = rows.first.scan(/[\.\#]/).length end def at(y, x) self.rows[y][x % width] end def tree?(y, x) at(y, x) == '#' end def each(&block) (0...self.rows.length).each(&block) end def height rows.length end private attr_accessor :width, :rows end grid = TreeGrid.from('input.txt') def count_trees(grid, slope_x, slope_y) trees = 0 x = 0 y = 0 while y < grid.height trees += 1 if grid.tree?(y, x) y += slope_y x += slope_x end trees end Benchmark.bmbm do |b| b.report do puts [ count_trees(grid, 1, 1), count_trees(grid, 3, 1), count_trees(grid, 5, 1), count_trees(grid, 7, 1), count_trees(grid, 1, 2) ].inject(&:*) end end
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is my Day 3 in Ruby