public
Last active

Project Euler - Problem 11 - Greatest product in grid

  • Download Gist
euler-011.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import Data.List(transpose,foldl')
 
subGridSize = 4
 
main = print
=<< return . result
=<< readFile "pb011-grid.txt"
 
result cs = maximum $ map maxGrid $ subgrids subGridSize
$ map (map read . words) $ lines cs
 
subgrids n = map transpose . concat .
map (slice n . transpose) . slice n
where slice n [] = []
slice n xs = takeWhile ((== n) . length)
$ (take n xs) : (slice n $ tail xs )
 
maxGrid xs = maximum [maxRows xs,
maxCols xs,
productMainDiagonal xs,
productSecondDiagonal xs]
where maxRows = maximum . map product
maxCols = maxRows . transpose
productMainDiagonal xs =
product [(xs!!i)!!i|i<-[0..(length xs)-1]]
productSecondDiagonal xs =
product [(xs!!i)!!(lasti-i)|i<-[0..lasti]]
lasti = (length xs) - 1

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.