1
0
Fork 0

Finish question 11 using lazy lists

main
Bill Ewanick 2023-09-15 01:32:20 -04:00
parent 7590b3c192
commit 38ba59c3e4
1 changed files with 58 additions and 0 deletions

View File

@ -26,6 +26,7 @@ The product of these numbers is 26x63x78x14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid? What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20x20 grid?
-} -}
import Data.List (genericDrop, genericIndex, genericTake)
grid :: [[Integer]] grid :: [[Integer]]
grid = grid =
@ -50,3 +51,60 @@ grid =
, [20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54] , [20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54]
, [01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48] , [01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]
] ]
points :: Integer -> [(Integer, Integer)]
points n = [ (x,y) | x <- [1..n], y <- [1..n] ]
allDiagonals :: Integer -> [[(Integer, Integer)]]
allDiagonals n =
[ [(i, j), b, c, d]
| (i, j) <- points n
, i+3 <= n
, j+3 <= n
, b <- [(i + 1, j + 1)]
, c <- [(i + 2, j + 2)]
, d <- [(i + 3, j + 3)]
]
allUpDown :: Integer -> [[(Integer, Integer)]]
allUpDown n =
[ [(i, j), b, c, d]
| (i, j) <- points n
, i <= n
, j+3 <= n
, b <- [(i, j + 1)]
, c <- [(i, j + 2)]
, d <- [(i, j + 3)]
]
allLeftRight :: Integer -> [[(Integer, Integer)]]
allLeftRight n =
[ [(i, j), b, c, d]
| (i, j) <- points n
, i+3 <= n
, j <= n
, b <- [(i + 1, j)]
, c <- [(i + 2, j)]
, d <- [(i + 3, j)]
]
allSequences :: Integer -> [[(Integer, Integer)]]
allSequences n = allDiagonals n ++ allUpDown n ++ allLeftRight n
s20x20 :: [[(Integer, Integer)]]
s20x20 = allSequences 20
getValue :: [[Integer]] -> (Integer, Integer) -> Integer
getValue grid (x,y) = row `genericIndex` y'
where row = (head . genericDrop (x-1) . genericTake x) grid
y' = y-1 -- compensate for 1 index numbering above
-- |
-- λ> ans
-- 51267216
-- (0.13 secs, 38,281,312 bytes)
ans :: Integer
ans = maximum $ map (product . map (getValue grid)) s20x20
main :: IO ()
main = print ans