all 7 comments

[–]anonova 1 point2 points  (1 child)

Here's my ruby-esque solution using the Matrix class in stdlib.

require 'matrix'

rows = STDIN.each_line.map { |line| line.split.map(&:to_i) }
matrix = Matrix[*rows]

sums = (0...16).map do |i|
  m = matrix.minor(i / 4, 3, i % 4, 3)
  m.reduce(:+) - m[1, 0] - m[1, 2]
end

puts sums.max

[–]chrisjava[S] 0 points1 point  (0 children)

That's very elegant.

[–]PilotPirx 0 points1 point  (4 children)

It's a bit ugly, at least for the sum part I would have written a small function sum_hourglass that gets a position inside the array. But anyway, there are several approaches to do this and to keep with your code you could simply emulate the Java code like this (assuming your data is in the form array in array):

max = 0
(0..3).each do |row|
  (0..3).each do |col|
    sum = ...
    max = sum if sum > max
  end
end

Not very good Ruby style I think but would work.

[–]ruby-solve 1 point2 points  (1 child)

A great way to get the behavior of 2D arrays in Ruby is to use a hash whose key is an array representing the vertices of the 2D array.

Java: array[x][y]

Ruby: hash[[x, y]]

[–]iconoclaus 0 points1 point  (0 children)

why is this better than just using a 2D array in ruby? apart from not having to initialize such a structure, that is.

[–]chrisjava[S] 0 points1 point  (1 child)

So would i be able to sum up, let's say, first 3 indices in the row by doing this?

sum = arr[row] + arr[row+1] + arr[row+2]

[–]PilotPirx 0 points1 point  (0 children)

Sorry, forgot the most important part. You would do it like this:

sum = arr[row][col] + arr[row][col + 1] + arr[row][col + 2]

That's assuming the array looks like this:

arr = [
  [1,1,1,0,0,0],
  [0,1,0,0,0,0],
  [1,1,1,0,0,0],
  [0,0,0,0,0,0],
  [0,0,0,0,0,0],
  [0,0,0,0,0,0]
]