Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- class Matrix
- attr_reader :x_size, :y_size
- def initialize(x_size, y_size)
- @x_size = x_size
- @y_size = y_size
- @data = @y_size.times.map{|y| @x_size.times.map{|x| block_given? ? yield(x,y) : 0 } }
- end
- def [](x,y)
- @data[y % @y_size][x % @x_size]
- end
- def flatten
- @data.flatten
- end
- end
- class Grid
- def initialize(data)
- @x_size = data[0].size
- @y_size = data.size
- raise "Not a rectangle" unless data.all?{|row| row.size == @x_size}
- @data = Matrix.new(@x_size, @y_size){|x,y| data[y][x]}
- end
- def [](x,y)
- @data[x,y]
- end
- def knights(counts, val)
- Matrix.new(@x_size, @y_size) do |x,y|
- if self[x,y] == val
- counts[x+2,y+1] + counts[x+1,y+2] +
- counts[x+2,y-1] + counts[x+1,y-2] +
- counts[x-2,y+1] + counts[x-1,y+2] +
- counts[x-2,y-1] + counts[x-1,y-2]
- else
- 0
- end
- end
- end
- def run!
- counts_1 = Matrix.new(@x_size, @y_size) do |x,y|
- if self[x,y] == "1"
- 1
- else
- 0
- end
- end
- counts_12 = knights(counts_1, "2")
- counts_123 = knights(counts_12, "3")
- counts_1234 = knights(counts_123, "4")
- p counts_1234.flatten.inject(&:+)
- end
- end
- grid = Grid.new(open("grid4.txt").read.split("\n"))
- grid.run!
Advertisement
Add Comment
Please, Sign In to add comment