The full description of the problem to solve can be found here. The code I have written works fine but seems extremely verbose for what it's doing, I'm not sure if list comprehensions are meant to be used in the way that I have (maybe some kind of other construct would be more suitable?). Would be great for there to be a way to make the numberPairs
function to be more DRY.
Also get the sense that I don't use function composition enough .
and instead use $
for most nested function calls. Is this bad practice? How could I rewrite some of the functions in this using composition?
I am fairly new to Haskell so am unaware of any typical coding practices.
gridOfNumbers
evaluates to a string containing the grid numbers from the problem with each number in a row separated by spaces and each row separated by newlines. Didn't seem worth including here (although I may be mistaken).
-- | In the `gridOfNumbers` find the 4 adjacent numbers in the given
-- | direction that have the greatest sum.
problem_11 :: Direction -> Int
problem_11 dir =
maximum $ map (\(x1,x2,x3,x4) -> product $ x1:x2:x3:x4:[]) $ numberPairs dir
data Direction = UpDown | SideWays | LeftStartDiagonal | RightStartDiagonal
numberPairs :: Direction -> [(Int,Int,Int,Int)]
numberPairs UpDown =
[(x1,x2,x3,x4) |
currentRow <- [0..16],
currentCol <- [0..19],
let x1 = (listifyGrid !! currentRow) !! currentCol,
let x2 = (listifyGrid !! (currentRow + 1)) !! currentCol,
let x3 = (listifyGrid !! (currentRow + 2)) !! currentCol,
let x4 = (listifyGrid !! (currentRow + 3)) !! currentCol]
numberPairs SideWays =
[(x1,x2,x3,x4) |
currentRow <- [0..19],
currentCol <- [0..16],
let x1 = (listifyGrid !! currentRow) !! currentCol,
let x2 = (listifyGrid !! currentRow) !! (currentCol + 1),
let x3 = (listifyGrid !! currentRow) !! (currentCol + 2),
let x4 = (listifyGrid !! currentRow) !! (currentCol + 3)]
numberPairs LeftStartDiagonal =
[(x1,x2,x3,x4) |
currentRow <- [0..16],
currentCol <- [0..16],
let x1 = (listifyGrid !! currentRow) !! currentCol,
let x2 = (listifyGrid !! (currentRow + 1)) !! (currentCol + 1),
let x3 = (listifyGrid !! (currentRow + 2)) !! (currentCol + 2),
let x4 = (listifyGrid !! (currentRow + 3)) !! (currentCol + 3)]
numberPairs RightStartDiagonal =
[(x1,x2,x3,x4) |
currentRow <- [0..16],
currentCol <- [3..19],
let x1 = (listifyGrid !! currentRow) !! currentCol,
let x2 = (listifyGrid !! (currentRow + 1)) !! (currentCol - 1),
let x3 = (listifyGrid !! (currentRow + 2)) !! (currentCol - 2),
let x4 = (listifyGrid !! (currentRow + 3)) !! (currentCol - 3)]
listifyGrid :: [[Int]]
listifyGrid = map (map read) doubleListOfStrings
where doubleListOfStrings = map (S.split " ") $ lines gridOfNumbers
product $ x1:x2:x3:x4:[]
could beproduct [x1,x2,x3,x4]
\$\endgroup\$