Snippet

project_euler/11.rb
Code:
# Project Euler Problem 11: Largest Product in a Grid

# https://projecteuler.net/problem=11

# In the 20 × 20 grid given, four numbers along a diagonal line
# have a product of 26 × 63 × 78 × 14 = 1788696.
# What is the greatest product of four adjacent numbers in the same direction
# (up, down, left, right, or diagonally) in the 20 × 20 grid?

require_relative './helpers.rb'

G, L = 20, 4

grid = get_dataset(problem: 11).map { |row| row.split(' ').map(&:to_i) }

def solve(grid)
    max = 0
    # horizontal
    grid.each { |r| (0..G-L).each { |d| max = [max, r[d, L].inject(:*)].max } }
    # vertical
    grid.transpose.each { |r| (0..G-L).each { |d| max = [max, r[d, L].inject(:*)].max } }
    # diagonal
    (0..G-L).each do |j|
        (0..G-L).each do |i|
            u = grid[j][i] * grid[j+1][i+1] * grid[j+2][i+2] * grid[j+3][i+3]
            d = grid[j][i] * grid[j-1][i+1] * grid[j-2][i+2] * grid[j-3][i+3]
            max = [max, u, d].max
        end
    end
    return max
end

puts solve(grid)
Output:
70600674