소스 검색

[Haskell][14] Adding Solution

Vinicius Teshima 5 달 전
부모
커밋
4ddb97ce46
1개의 변경된 파일38개의 추가작업 그리고 0개의 파일을 삭제
  1. 38 0
      haskell/src/0014.hs

+ 38 - 0
haskell/src/0014.hs

@@ -0,0 +1,38 @@
+{-
+The following iterative sequence is defined for the set of positive integers:
+n -> n/2 (n is even)
+n -> 3n + 1 (n is odd)
+Using the rule above and starting with 13, we generate the following sequence:
+13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1.
+It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
+Which starting number, under one million, produces the longest chain?
+NOTE: Once the chain starts the terms are allowed to go above one million.
+-}
+
+import Data.List
+import Data.Maybe
+import Data.Function
+
+(|>) = (&)
+
+next_term :: Int -> Int
+next_term 1 = 1
+next_term x
+  | even x    = div x 2
+  | otherwise = (x * 3) + 1
+
+gen_chain :: Int -> [Int]
+gen_chain 1 = [1]
+gen_chain s = [s] ++ gen_chain (next_term s)
+
+solution :: Int
+solution = chains !! (elemIndex biggest chains_size |> fromJust) |> head
+  where
+    chains = [1..1000000] |> map gen_chain
+    -- For some reason if chains is used here it will fill all the memory
+    chains_size = [1..1000000] |> map gen_chain |> map length
+    biggest :: Int
+    biggest = maximum chains_size
+
+main :: IO ()
+main = putStrLn ("Solution: " ++ show solution)