Skip to content

Commit

Permalink
Solved trampoline problem for day 5
Browse files Browse the repository at this point in the history
This included learning more about Sequence and Array data structures
for performance as List "mutation" was very slow. Seq data structure
was enough to run nearly 50% faster than the equivalent python code.

> $ time python day05.py
> 21841249
>
> real	0m14.671s
> user	0m14.646s
> sys	0m0.015s
>
> $ time result/bin/trampoline
> 21841249
>
> real	0m7.478s
> user	0m7.422s
> sys	0m0.048s
  • Loading branch information
jsamsa committed Mar 24, 2018
1 parent 556152c commit 7a108b9
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 4 deletions.
Empty file added LICENSE
Empty file.
11 changes: 11 additions & 0 deletions aoc2017.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: aoc2017
version: 1.0.0
license: BSD3
license-file: LICENSE
cabal-version: >= 1.18
build-type: Simple

executable trampoline
build-depends: base < 5, mtl, containers, array
main-is: day05-trampoline.hs
default-language: Haskell2010
38 changes: 34 additions & 4 deletions day05-trampoline.hs
Original file line number Diff line number Diff line change
@@ -1,10 +1,40 @@
module Main where

import qualified Data.Sequence as S

data JumpState = JumpState { moves :: [Int], cursor :: Int }
type Cursor = Int
type Count = Int


-- startState = (0, 0, [0,3,0,1,-3])

inside :: Int -> S.Seq Int -> Bool
inside idx xs = idx >= 0 && idx < S.length xs


mutate :: Int -> S.Seq Int -> S.Seq Int
mutate cursor xs = S.adjust inc cursor xs

mutate' :: Int -> S.Seq Int -> S.Seq Int
mutate' cursor xs = S.adjust (if (S.index xs cursor) > 2 then dec else inc) cursor xs

dec :: Int -> Int
dec n = n - 1

inc :: Int -> Int
inc n = n + 1


jump :: Count -> Cursor -> S.Seq Int -> Count
jump count cursor xs
| inside cursor xs = count `seq` cursor `seq` jump (inc count)
(cursor + (S.index xs cursor))
(mutate' cursor xs)
| otherwise = count

main :: IO ()
main = do
input <- readFile "day05.txt"
let jumps = map read $ lines input :: [Int]
print $ show $ length jumps
strings <- words <$> readFile "../AoC2017/day05.txt"
--let strings = words "0 3 0 1 -3"
print $ jump 0 0 (S.fromList (map read strings :: [Int]))

28 changes: 28 additions & 0 deletions day05.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

def inside(idx, xs):
return not (idx < 0 or idx >= len(xs))


testList = [0,3,0,1,-3]
count = 0
cursor = 0

f = open("day05.txt")
testList = []

for line in f:
testList.append(int(line))

while (inside(cursor, testList)):
count += 1
offset = testList[cursor]
if (offset > 2):
testList[cursor] -= 1
else:
testList[cursor] += 1
cursor += offset
print (count)




0 comments on commit 7a108b9

Please sign in to comment.