t_a_w

Grid 4 - knights

Apr 19th, 2016
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.31 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2.  
  3. class Matrix
  4.   attr_reader :x_size, :y_size
  5.   def initialize(x_size, y_size)
  6.     @x_size = x_size
  7.     @y_size = y_size
  8.     @data = @y_size.times.map{|y| @x_size.times.map{|x| block_given? ? yield(x,y) : 0 } }
  9.   end
  10.  
  11.   def [](x,y)
  12.     @data[y % @y_size][x % @x_size]
  13.   end
  14.  
  15.   def flatten
  16.     @data.flatten
  17.   end
  18. end
  19.  
  20. class Grid
  21.   def initialize(data)
  22.     @x_size = data[0].size
  23.     @y_size = data.size
  24.     raise "Not a rectangle" unless data.all?{|row| row.size == @x_size}
  25.     @data = Matrix.new(@x_size, @y_size){|x,y| data[y][x]}
  26.   end
  27.  
  28.   def [](x,y)
  29.     @data[x,y]
  30.   end
  31.  
  32.   def knights(counts, val)
  33.     Matrix.new(@x_size, @y_size) do |x,y|
  34.       if self[x,y] == val
  35.         counts[x+2,y+1] + counts[x+1,y+2] +
  36.         counts[x+2,y-1] + counts[x+1,y-2] +
  37.         counts[x-2,y+1] + counts[x-1,y+2] +
  38.         counts[x-2,y-1] + counts[x-1,y-2]
  39.       else
  40.         0
  41.       end
  42.     end
  43.   end
  44.  
  45.   def run!
  46.     counts_1 = Matrix.new(@x_size, @y_size) do |x,y|
  47.       if self[x,y] == "1"
  48.         1
  49.       else
  50.         0
  51.       end
  52.     end
  53.     counts_12 = knights(counts_1, "2")
  54.     counts_123 = knights(counts_12, "3")
  55.     counts_1234 = knights(counts_123, "4")
  56.     p counts_1234.flatten.inject(&:+)
  57.   end
  58. end
  59.  
  60. grid = Grid.new(open("grid4.txt").read.split("\n"))
  61. grid.run!
Advertisement
Add Comment
Please, Sign In to add comment