From bc28995115a02e665cb8d9cc8228f21ace5319f3 Mon Sep 17 00:00:00 2001 From: Bill Ewanick Date: Wed, 27 Sep 2023 16:51:16 -0400 Subject: [PATCH] Add performance improvement --- src/projectEuler/question14.hs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/projectEuler/question14.hs b/src/projectEuler/question14.hs index 34cf393..a4128ed 100644 --- a/src/projectEuler/question14.hs +++ b/src/projectEuler/question14.hs @@ -16,14 +16,14 @@ NOTE: Once the chain starts the terms are allowed to go above one million. -} module Main where -import Data.List (sortOn) +import Data.List (genericLength, sortOn) import Data.Ord (Down (Down)) main :: IO () main = print ans ans :: Integer -ans = head $ head $ sortOn (Down . length) $ map collatzChainStartingAt [1..limit] +ans = fst $ head $ sortOn (Down . snd) $ map collatzChainStartingAt [1..limit] nextCollatz :: Integer -> Integer nextCollatz n @@ -31,8 +31,9 @@ nextCollatz n | even n = n `div` 2 | odd n = 3*n + 1 -collatzChainStartingAt :: Integer -> [Integer] -collatzChainStartingAt n = takeWhile (/= 0) $ iterate nextCollatz n +collatzChainStartingAt :: Integer -> (Integer, Integer) +collatzChainStartingAt n = (n, s') + where s' = genericLength $ takeWhile (/= 0) $ iterate nextCollatz n limit :: Integer limit = 1_000_000