Skip to content

Instantly share code, notes, and snippets.

@elreimundo
Created July 20, 2013 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elreimundo/6046335 to your computer and use it in GitHub Desktop.
Save elreimundo/6046335 to your computer and use it in GitHub Desktop.
This is the main method for a ProjectEuler problem that provides a grid of numbers (copied and pasted as a string) and wants to find the maximum product of any four consecutive elements horizontally, vertically, or diagonally. I probably could have written each of the if/then statements in a single line, but executing two lines of code actually …
def largestproduct(nums_as_a_string)
currentmax = 0
arry = nums_as_a_string.split("\n")
arry.map! { |row_as_a_string| row_as_a_string.split.map! { |digit| digit.to_i } }
0.upto( (arry.length - 1).to_i ) do |row|
0.upto( (arry[row].length - 1).to_i ) do |col|
if col <= (arry[row].length - 4)
rowprod = arry[row][col]*arry[row][col+1]*arry[row][col+2]*arry[row][col+3]
currentmax = [currentmax,rowprod].max
end
if row <= (arry.length - 4)
colprod = arry[row][col]*arry[row+1][col]*arry[row+2][col]*arry[row+3][col]
currentmax = [currentmax,colprod].max
if col <= arry[row].length - 4
drprod = arry[row][col]*arry[row+1][col+1]*arry[row+2][col+2]*arry[row+3][col+3]
currentmax = [currentmax,drprod].max
end
if col >=3
dlprod = arry[row][col]*arry[row+1][col-1]*arry[row+2][col-2]*arry[row+3][col-3]
currentmax = [currentmax,dlprod].max
end
end
end
end
currentmax
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment