Last Facebook Ruby Code – Grids

I promise, in remembering how much I don’t like optimization problems, I was playing around with the Facebook Grid Puzzle. Now I’m done looking at the Facebook problems, but in case anybody else is interested in playing around, here is some Ruby code I wrote that models the problem exactly:

Also, as an aside, I’ve noticed http://snippets.dzone.com/ showing up in search results lately and it has lots of interesting examples, without all of the ugliness of devshed or any of that garbage. Although its all tagging and not searchable – dumb.

class Grid
   attr_reader :two_d_array, :col_sum_array, :row_sum_array, :big_S

   def initialize(two_d_array)
      @two_d_array = two_d_array
      @col_sum_array = []
      @row_sum_array = []
      @big_S = 0
   end

   def calculations
      @col_sum_array = []
      @row_sum_array = []
      @big_S = 0
      col_krem = Array.new
      row_krem = Array.new
      two_d_array.each_with_index do |row, index|
         col_sub = 0
         row_sub = 0
         two_d_array[index].each_with_index do |col,i|
            col_sub += two_d_array[i][index]
            row_sub += two_d_array[index][i]
         end
         @col_sum_array < < col_sub
         @row_sum_array << row_sub
         @big_S = @big_S + col_sub + row_sub
         p two_d_array[index]
      end
   end

   def flip_row(row_num)
     @two_d_array[row_num].each_with_index  do |v, index|
        @two_d_array[row_num][index] = v * -1
     end
     self.calculations
   end

   def flip_col(col_num)
     for i in (0...@two_d_array.length)
         @two_d_array[i][col_num] = @two_d_array[i][col_num] * -1
     end
     self.calculations
   end

end

two_d_array = Grid.new([ [3,1,-5,-3,4],[4,-5,-2,-3,-3],[6,-8,-2,-6,1],[3,4,1,-4,-8],[1,4,-2,7,-1] ])

puts "Initial Array"
puts "-------------"
two_d_array.calculations
puts "-------------"
puts "Initial Big S: #{two_d_array.big_S}"

puts "------------"
puts "------------"
puts "Flipping Row Zero"
puts "------------"
two_d_array.flip_row(0)

puts "------------"
puts "------------"
puts "Flipping Column One"
puts "------------"
two_d_array.flip_col(1)

puts "------------"
puts "------------"
puts "Column Sum Array"
p two_d_array.col_sum_array
puts "------------"
puts "Row Sum Array"
p two_d_array.row_sum_array
puts "------------"
puts "Big S: #{two_d_array.big_S}"
posted on Wednesday, July 4th, 2007 by Tyler in Code For Fun

0 Comments

Leave Comment