Browse Source

Refactored Day 01

With Data.IntSet from containers (sorted) part 2 now takes 1 second instead of 2 Minutes *yay*
Nicolas Lenz 3 months ago
parent
commit
75e48d454a
3 changed files with 20 additions and 11 deletions
  1. 3
    0
      advent-of-code.cabal
  2. 2
    0
      package.yaml
  3. 15
    11
      src/Day01.hs

+ 3
- 0
advent-of-code.cabal View File

@@ -4,7 +4,7 @@ cabal-version: 1.12
4 4
 --
5 5
 -- see: https://github.com/sol/hpack
6 6
 --
7
+-- hash: a31d69558fb7c391bf70ef12c046d4b4a10a2fd42e24f572cc4592799a825b1b
7 8
 
8 9
 name:           advent-of-code
9 10
 version:        0.0.0
@@ -37,5 +37,7 @@ executable advent-of-code
37 37
   ghc-options: -O2 -threaded -rtsopts -with-rtsopts=-N
38 38
   build-depends:
39 39
       base >=4.7 && <5
40
+    , containers
41
+    , parsec
40 42
     , text
41 43
   default-language: Haskell2010

+ 2
- 0
package.yaml View File

@@ -16,6 +16,8 @@ description:         Please see the README at <https://git.eisfunke.com/research
16 16
 dependencies:
17 17
 - base >= 4.7 && < 5
18 18
 - text
19
+- containers
20
+- parsec
19 21
 
20 22
 executables:
21 23
   advent-of-code:

+ 15
- 11
src/Day01.hs View File

@@ -1,11 +1,17 @@
1 1
 module Day01 (part1, part2) where
2 2
 
3
+import Data.IntSet (IntSet)
4
+import qualified Data.IntSet as IntSet
5
+
3 6
 
4 7
 part1 :: [String] -> String
5
-part1 input = show $ last $ applySeq (toFunction <$> input) 0
8
+part1 input = show $ last $ scanl (flip ($)) 0 (toFunction <$> input)
6 9
 
7 10
 part2 :: [String] -> String
8
-part2 input = show $ firstTwice $ applySeq (cycle (toFunction <$> input)) 0
11
+part2 input = show $ firstTwice $ scanl (flip ($)) 0 (toFunction <$> cycle input)
12
+
13
+example :: [String]
14
+example = ["+1", "-2", "+3", "+1"]
9 15
 
10 16
 
11 17
 -- |Parses a String like "+32" or "-23" to the corresponding function.
@@ -13,15 +19,11 @@ toFunction :: String -> (Int -> Int)
13 19
 toFunction ('+':as) = (+(read as))
14 20
 toFunction ('-':as) = (\x -> x - read as)
15 21
 
16
-applySeq :: [a -> a] -> a -> [a]
17
-applySeq [] start = [start]
18
-applySeq (f:fs) start = start : applySeq fs (f start)
19
-
20
-firstTwice :: Eq a => [a] -> Maybe a
21
-firstTwice as = loop as [] where
22
+-- |Finds the first element that occurs twice in a list. Works on infinite lists (but in that case doesn't terminate if there's no element occuring twice).
23
+firstTwice :: [Int] -> Maybe Int
24
+firstTwice as = loop as IntSet.empty where
25
+    loop :: [Int] -> IntSet -> Maybe Int
22 26
     loop [] found = Nothing
23
-    loop todo@(x:xs) found
24
-        | x `elem` found = Just x
25
-        | otherwise = loop xs (x:found)
27
+    loop (x:xs) found
28
+        | x `IntSet.member` found = Just x
29
+        | otherwise = loop xs (x `IntSet.insert` found)

Loading…
Cancel
Save