Skip to content

Commit 4131bc2

Browse files
committed
Slightly (0.1s better under optimizations) more efficient cycle detection
1 parent bc7992c commit 4131bc2

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

14.hs

+10-6
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,16 @@ f s = let (a, b) = span (/= '#') s
1717
in reverse (sort a) ++ c ++ f d
1818

1919
cycle1 = east . south . west . north
20-
cycle1B = go 1000000000 []
21-
where go n prev xs = let ys = cycle1 xs in case findIndex (==ys) prev of
22-
Nothing -> go n (prev ++ [ys]) ys
23-
Just i -> let cycleLength = length prev - i
24-
remain = (n - i) `mod` cycleLength
25-
in (\(h:_) -> h) $ drop (remain - 1) (drop i prev)
20+
cycle1B xs = go 1000000000 [(load xs, xs)] xs
21+
where
22+
go n prev xs =
23+
let key = (load &&& id) $ cycle1 xs in case findIndex (==key) prev of
24+
Nothing -> go n (key : prev) (snd key)
25+
Just i ->
26+
let cycleLength = i + 1
27+
offset = length prev - (i + 1)
28+
remain = (n - offset) `mod` cycleLength
29+
in (\(h:_)-> snd h) $ drop remain $ drop offset $ reverse prev
2630

2731
load :: [String] -> Int
2832
load = sum . map g . countdown

0 commit comments

Comments
 (0)