--- /dev/null
+-- Writeup at https://work.njae.me.uk/2022/12/19/advent-of-code-2022-day-17/
+
+-- import Debug.Trace
+
+import AoC
+import qualified Data.Set as S
+import qualified Data.Map.Strict as M
+import Linear hiding (Trace, trace, distance)
+import Control.Lens
+import Data.Maybe
+
+type Position = V2 Int -- x, y; y increasing upwards
+type Chamber = S.Set Position
+type Rock = S.Set Position
+
+data SimulationState = SimulationState
+ { _chamber :: Chamber
+ , _jets :: [Position]
+ , _rocks :: [Rock]
+ , _droppedCount :: Int
+ } deriving (Eq, Ord)
+makeLenses ''SimulationState
+
+instance Show SimulationState where
+ show sState = "SimState { _chamber = "
+ ++ (show $ sState ^. chamber)
+ ++ ", _jets = "
+ ++ (show (take 5 (sState ^. jets)))
+ ++ ", _rocks = "
+ ++ (show (take 5 (sState ^. rocks)))
+ ++ ", _droppedCount = "
+ ++ (show (sState ^. droppedCount))
+ ++ " }"
+
+main :: IO ()
+main =
+ do dataFileName <- getDataFileName
+ text <- readFile dataFileName
+ let oneJetCycle = mkJets text
+ print $ part1 oneJetCycle
+ -- print $ (length oneJetCycle) * (length rockPics)
+ print $ part2 oneJetCycle
+
+part1, part2 :: [Position] -> Int
+part1 oneJetCycle = rocksHeight final -- fromMaybe -1 $ maximumOf (folded . _y) (final ^. chamber)
+ where final = simulate mkRocks (cycle oneJetCycle) 2022
+
+part2 oneJetCycle = calculatedHeight -- (cycleStartState, cycleRepeatState)
+ where initState = SimulationState
+ { _chamber = S.empty
+ , _jets = (cycle oneJetCycle)
+ , _rocks = mkRocks
+ , _droppedCount = 0
+ }
+ (cycleStartState, _) = findEarliestRepeat (length oneJetCycle) initState
+ cycleRepeatState = findCycleRepeat (length oneJetCycle) cycleStartState
+ cycleStart = cycleStartState ^. droppedCount
+ cycleLength = (cycleRepeatState ^. droppedCount) - cycleStart
+ startHeight = rocksHeight cycleStartState
+ differenceHeight = (rocksHeight cycleRepeatState) - startHeight
+ afterStart = 1000000000000 - cycleStart
+ (numCycles, remainingDrops) = afterStart `divMod` cycleLength
+ finalState = (!!remainingDrops) $ iterate dropFromTop cycleStartState
+ finalHeight = rocksHeight finalState
+ calculatedHeight = finalHeight + (differenceHeight * numCycles)
+
+rocksHeight :: SimulationState -> Int
+rocksHeight state = fromMaybe -1 $ maximumOf (folded . _y) (state ^. chamber)
+
+simSome :: [Position] -> Int -> Int
+simSome oneJetCycle n = fromMaybe -1 $ maximumOf (folded . _y) (final ^. chamber)
+ where final = simulate mkRocks (cycle oneJetCycle) n
+
+simulate :: [Rock] -> [Position] -> Int -> SimulationState
+simulate rocks jets n = (!!n) $ iterate dropFromTop initState
+ where initState = SimulationState { _chamber = S.empty, _jets = jets, _rocks = rocks, _droppedCount = 0}
+
+dropFromTop :: SimulationState -> SimulationState
+dropFromTop simState = (dropRock simState (initialPlace simState))
+ & rocks %~ tail
+ & droppedCount %~ (+ 1)
+
+dropRock :: SimulationState -> Rock -> SimulationState
+dropRock simState rock
+ | rock2 == Nothing = simState & chamber %~ (S.union rock1)
+ & jets %~ tail
+ | otherwise = dropRock (simState & jets %~ tail) $ fromJust rock2
+ where rock1 = push (simState ^. chamber) rock (head (simState ^. jets))
+ rock2 = fall (simState ^. chamber) rock1
+
+initialPlace :: SimulationState -> Rock
+initialPlace simState = S.map (^+^ (V2 2 startHeight)) rock
+ where startHeight = 4 + (fromMaybe 0 $ maximumOf (folded . _y) (simState ^. chamber))
+ rock = head $ simState ^. rocks
+
+push :: Chamber -> Rock -> Position -> Rock
+push chamber rock direction
+ -- | trace ("Before push " ++ (intercalate " : " $ [show chamber, show rock, show direction])) False = undefined
+ | disjoint && inLeft && inRight = pushedRock
+ | otherwise = rock
+ where pushedRock = S.map (^+^ direction) rock
+ disjoint = S.null $ S.intersection pushedRock chamber
+ inLeft = (fromJust $ minimumOf (folded . _x) pushedRock) >= 0
+ inRight = (fromJust $ maximumOf (folded . _x) pushedRock) <= 6
+
+fall :: Chamber -> Rock -> Maybe Rock
+fall chamber rock
+ -- | trace ("Before fall " ++ (intercalate " : " $ [show chamber, show rock, show disjoint, show aboveFloor, show droppedRock])) False = undefined
+ | disjoint && aboveFloor = Just droppedRock
+ | otherwise = Nothing
+ where droppedRock = S.map (^+^ (V2 0 -1)) rock
+ disjoint = S.null $ S.intersection droppedRock chamber
+ aboveFloor = (fromJust $ minimumOf (folded . _y) droppedRock) > 0
+
+
+findCycleRepeat :: Int -> SimulationState -> SimulationState
+findCycleRepeat jetLength cycleStart = head $ dropWhile (differentProfiles jetLength cycleStart) hares
+ where hares = drop 1 $ iterate dropFromTop cycleStart
+
+
+findEarliestRepeat :: Int -> SimulationState -> (SimulationState, SimulationState)
+findEarliestRepeat jetLength simState = head $ dropWhile (uncurry (differentProfiles jetLength)) pairs
+ where tortoises = drop 1 $ iterate dropFromTop simState
+ hares = drop 1 $ iterate (dropFromTop . dropFromTop) simState
+ pairs = zip tortoises hares
+
+differentProfiles :: Int -> SimulationState -> SimulationState -> Bool
+differentProfiles jetLength t h = (simulationProfile jetLength t) /= (simulationProfile jetLength h)
+
+simulationProfile :: Int -> SimulationState -> (Chamber, [Position], Rock)
+simulationProfile jetLength state =
+ ( surfaceProfile state
+ , take jetLength $ state ^. jets
+ , head $ state ^. rocks
+ )
+
+surfaceProfile :: SimulationState -> Chamber
+surfaceProfile state = S.fromList $ map (^-^ (V2 0 peak)) rawProfile
+ where ch = state ^. chamber
+ rawProfile = [V2 i (fromMaybe -1 $ maximumOf (folded . filteredBy (_x . only i) . _y) ch) | i <- [0..6] ]
+ peak = fromJust $ maximumOf (folded . _y) rawProfile
+
+showChamber :: Chamber -> String
+showChamber chamber = unlines
+ [ [showCell x y | x <- [0..6]]
+ | y <- reverse [1..yMax]
+ ] ++ "-------"
+ where yMax = fromMaybe 0 $ maximumOf (folded . _y) chamber
+ showCell x y
+ | (V2 x y) `S.member` chamber = '#'
+ | otherwise = '.'
+
+mkJets :: String -> [Position]
+mkJets = fmap mkJet
+ where mkJet '<' = V2 -1 0
+ mkJet '>' = V2 1 0
+ mkJet _ = error "Illegal jet character"
+
+mkRocks :: [Rock]
+mkRocks = cycle $ fmap mkRock rockPics
+
+mkRock :: String -> Rock
+mkRock rockPic = S.fromList
+ [ V2 x y
+ | x <- [0..((length (rockLines!!0)) - 1)]
+ , y <- [0..((length rockLines) - 1)]
+ , (rockLines!!y)!!x == '#'
+ ]
+ where rockLines = reverse $ lines rockPic
+
+rockPics :: [String]
+rockPics = ["####", ".#.\n###\n.#.", "..#\n..#\n###", "#\n#\n#\n#", "##\n##"]
+
--- /dev/null
+<!DOCTYPE html>
+<html lang="en-us">
+<head>
+<meta charset="utf-8"/>
+<title>Day 17 - Advent of Code 2022</title>
+<!--[if lt IE 9]><script src="/static/html5.js"></script><![endif]-->
+<link href='//fonts.googleapis.com/css?family=Source+Code+Pro:300&subset=latin,latin-ext' rel='stylesheet' type='text/css'/>
+<link rel="stylesheet" type="text/css" href="/static/style.css?30"/>
+<link rel="stylesheet alternate" type="text/css" href="/static/highcontrast.css?0" title="High Contrast"/>
+<link rel="shortcut icon" href="/favicon.png"/>
+<script>window.addEventListener('click', function(e,s,r){if(e.target.nodeName==='CODE'&&e.detail===3){s=window.getSelection();s.removeAllRanges();r=document.createRange();r.selectNodeContents(e.target);s.addRange(r);}});</script>
+</head><!--
+
+
+
+
+Oh, hello! Funny seeing you here.
+
+I appreciate your enthusiasm, but you aren't going to find much down here.
+There certainly aren't clues to any of the puzzles. The best surprises don't
+even appear in the source until you unlock them for real.
+
+Please be careful with automated requests; I'm not a massive company, and I can
+only take so much traffic. Please be considerate so that everyone gets to play.
+
+If you're curious about how Advent of Code works, it's running on some custom
+Perl code. Other than a few integrations (auth, analytics, social media), I
+built the whole thing myself, including the design, animations, prose, and all
+of the puzzles.
+
+The puzzles are most of the work; preparing a new calendar and a new set of
+puzzles each year takes all of my free time for 4-5 months. A lot of effort
+went into building this thing - I hope you're enjoying playing it as much as I
+enjoyed making it for you!
+
+If you'd like to hang out, I'm @ericwastl on Twitter.
+
+- Eric Wastl
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+-->
+<body>
+<header><div><h1 class="title-global"><a href="/">Advent of Code</a></h1><nav><ul><li><a href="/2022/about">[About]</a></li><li><a href="/2022/events">[Events]</a></li><li><a href="https://teespring.com/stores/advent-of-code" target="_blank">[Shop]</a></li><li><a href="/2022/settings">[Settings]</a></li><li><a href="/2022/auth/logout">[Log Out]</a></li></ul></nav><div class="user">Neil Smith <a href="/2022/support" class="supporter-badge" title="Advent of Code Supporter">(AoC++)</a> <span class="star-count">34*</span></div></div><div><h1 class="title-event"> <span class="title-event-wrap">0xffff&</span><a href="/2022">2022</a><span class="title-event-wrap"></span></h1><nav><ul><li><a href="/2022">[Calendar]</a></li><li><a href="/2022/support">[AoC++]</a></li><li><a href="/2022/sponsors">[Sponsors]</a></li><li><a href="/2022/leaderboard">[Leaderboard]</a></li><li><a href="/2022/stats">[Stats]</a></li></ul></nav></div></header>
+
+<div id="sidebar">
+<div id="sponsor"><div class="quiet">Our <a href="/2022/sponsors">sponsors</a> help make Advent of Code possible:</div><div class="sponsor"><a href="https://optiver.com/advent-of-code" target="_blank" onclick="if(ga)ga('send','event','sponsor','sidebar',this.href);" rel="noopener">Optiver</a> - Love solving puzzles? So do we! We're hiring engineers to code trading systems with sub-nanosecond performance. Get ready for daily challenges, continuous learning and the freedom to bring your software solutions to life</div></div>
+</div><!--/sidebar-->
+
+<main>
+<article class="day-desc"><h2>--- Day 17: Pyroclastic Flow ---</h2><p>Your handheld device has located an alternative exit from the cave for you and the elephants. The ground is rumbling almost continuously now, but the strange valves bought you some time. It's definitely getting warmer in here, though.</p>
+<p>The tunnels eventually open into a very tall, narrow chamber. Large, oddly-shaped rocks are falling into the chamber from above, presumably due to all the rumbling. If you can't work out where the rocks will fall next, you might be <span title="I am the man who arranges the blocks / that descend upon me from up above!">crushed</span>!</p>
+<p>The five types of rocks have the following peculiar shapes, where <code>#</code> is rock and <code>.</code> is empty space:</p>
+<pre><code>####
+
+.#.
+###
+.#.
+
+..#
+..#
+###
+
+#
+#
+#
+#
+
+##
+##
+</code></pre>
+<p>The rocks fall in the order shown above: first the <code>-</code> shape, then the <code>+</code> shape, and so on. Once the end of the list is reached, the same order repeats: the <code>-</code> shape falls first, sixth, 11th, 16th, etc.</p>
+<p>The rocks don't spin, but they do get pushed around by jets of hot gas coming out of the walls themselves. A quick scan reveals the effect the jets of hot gas will have on the rocks as they fall (your puzzle input).</p>
+<p>For example, suppose this was the jet pattern in your cave:</p>
+<pre><code>>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>
+</code></pre>
+<p>In jet patterns, <code><</code> means a push to the left, while <code>></code> means a push to the right. The pattern above means that the jets will push a falling rock right, then right, then right, then left, then left, then right, and so on. If the end of the list is reached, it repeats.</p>
+<p>The tall, vertical chamber is exactly <em>seven units wide</em>. Each rock appears so that its left edge is two units away from the left wall and its bottom edge is three units above the highest rock in the room (or the floor, if there isn't one).</p>
+<p>After a rock appears, it alternates between <em>being pushed by a jet of hot gas</em> one unit (in the direction indicated by the next symbol in the jet pattern) and then <em>falling one unit down</em>. If any movement would cause any part of the rock to move into the walls, floor, or a stopped rock, the movement instead does not occur. If a <em>downward</em> movement would have caused a falling rock to move into the floor or an already-fallen rock, the falling rock stops where it is (having landed on something) and a new rock immediately begins falling.</p>
+<p>Drawing falling rocks with <code>@</code> and stopped rocks with <code>#</code>, the jet pattern in the example above manifests as follows:</p>
+<pre><code>The first rock begins falling:
+|..@@@@.|
+|.......|
+|.......|
+|.......|
++-------+
+
+Jet of gas pushes rock right:
+|...@@@@|
+|.......|
+|.......|
+|.......|
++-------+
+
+Rock falls 1 unit:
+|...@@@@|
+|.......|
+|.......|
++-------+
+
+Jet of gas pushes rock right, but nothing happens:
+|...@@@@|
+|.......|
+|.......|
++-------+
+
+Rock falls 1 unit:
+|...@@@@|
+|.......|
++-------+
+
+Jet of gas pushes rock right, but nothing happens:
+|...@@@@|
+|.......|
++-------+
+
+Rock falls 1 unit:
+|...@@@@|
++-------+
+
+Jet of gas pushes rock left:
+|..@@@@.|
++-------+
+
+Rock falls 1 unit, causing it to come to rest:
+|..####.|
++-------+
+
+A new rock begins falling:
+|...@...|
+|..@@@..|
+|...@...|
+|.......|
+|.......|
+|.......|
+|..####.|
++-------+
+
+Jet of gas pushes rock left:
+|..@....|
+|.@@@...|
+|..@....|
+|.......|
+|.......|
+|.......|
+|..####.|
++-------+
+
+Rock falls 1 unit:
+|..@....|
+|.@@@...|
+|..@....|
+|.......|
+|.......|
+|..####.|
++-------+
+
+Jet of gas pushes rock right:
+|...@...|
+|..@@@..|
+|...@...|
+|.......|
+|.......|
+|..####.|
++-------+
+
+Rock falls 1 unit:
+|...@...|
+|..@@@..|
+|...@...|
+|.......|
+|..####.|
++-------+
+
+Jet of gas pushes rock left:
+|..@....|
+|.@@@...|
+|..@....|
+|.......|
+|..####.|
++-------+
+
+Rock falls 1 unit:
+|..@....|
+|.@@@...|
+|..@....|
+|..####.|
++-------+
+
+Jet of gas pushes rock right:
+|...@...|
+|..@@@..|
+|...@...|
+|..####.|
++-------+
+
+Rock falls 1 unit, causing it to come to rest:
+|...#...|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+A new rock begins falling:
+|....@..|
+|....@..|
+|..@@@..|
+|.......|
+|.......|
+|.......|
+|...#...|
+|..###..|
+|...#...|
+|..####.|
++-------+
+</code></pre>
+<p>The moment each of the next few rocks begins falling, you would see this:</p>
+<pre><code>|..@....|
+|..@....|
+|..@....|
+|..@....|
+|.......|
+|.......|
+|.......|
+|..#....|
+|..#....|
+|####...|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|..@@...|
+|..@@...|
+|.......|
+|.......|
+|.......|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|..@@@@.|
+|.......|
+|.......|
+|.......|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|...@...|
+|..@@@..|
+|...@...|
+|.......|
+|.......|
+|.......|
+|.####..|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|....@..|
+|....@..|
+|..@@@..|
+|.......|
+|.......|
+|.......|
+|..#....|
+|.###...|
+|..#....|
+|.####..|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|..@....|
+|..@....|
+|..@....|
+|..@....|
+|.......|
+|.......|
+|.......|
+|.....#.|
+|.....#.|
+|..####.|
+|.###...|
+|..#....|
+|.####..|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|..@@...|
+|..@@...|
+|.......|
+|.......|
+|.......|
+|....#..|
+|....#..|
+|....##.|
+|....##.|
+|..####.|
+|.###...|
+|..#....|
+|.####..|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+
+|..@@@@.|
+|.......|
+|.......|
+|.......|
+|....#..|
+|....#..|
+|....##.|
+|##..##.|
+|######.|
+|.###...|
+|..#....|
+|.####..|
+|....##.|
+|....##.|
+|....#..|
+|..#.#..|
+|..#.#..|
+|#####..|
+|..###..|
+|...#...|
+|..####.|
++-------+
+</code></pre>
+<p>To prove to the elephants your simulation is accurate, they want to know how tall the tower will get after 2022 rocks have stopped (but before the 2023rd rock begins falling). In this example, the tower of rocks will be <code><em>3068</em></code> units tall.</p>
+<p><em>How many units tall will the tower of rocks be after 2022 rocks have stopped falling?</em></p>
+</article>
+<p>Your puzzle answer was <code>3211</code>.</p><article class="day-desc"><h2 id="part2">--- Part Two ---</h2><p>The elephants are not impressed by your simulation. They demand to know how tall the tower will be after <code><em>1000000000000</em></code> rocks have stopped! Only then will they feel confident enough to proceed through the cave.</p>
+<p>In the example above, the tower would be <code><em>1514285714288</em></code> units tall!</p>
+<p><em>How tall will the tower be after <code>1000000000000</code> rocks have stopped?</em></p>
+</article>
+<p>Your puzzle answer was <code>1589142857183</code>.</p><p class="day-success">Both parts of this puzzle are complete! They provide two gold stars: **</p>
+<p>At this point, you should <a href="/2022">return to your Advent calendar</a> and try another puzzle.</p>
+<p>If you still want to see it, you can <a href="17/input" target="_blank">get your puzzle input</a>.</p>
+<p>You can also <span class="share">[Share<span class="share-content">on
+ <a href="https://twitter.com/intent/tweet?text=I%27ve+completed+%22Pyroclastic+Flow%22+%2D+Day+17+%2D+Advent+of+Code+2022&url=https%3A%2F%2Fadventofcode%2Ecom%2F2022%2Fday%2F17&related=ericwastl&hashtags=AdventOfCode" target="_blank">Twitter</a>
+ <a href="javascript:void(0);" onclick="var mastodon_instance=prompt('Mastodon Instance / Server Name?'); if(typeof mastodon_instance==='string' && mastodon_instance.length){this.href='https://'+mastodon_instance+'/share?text=I%27ve+completed+%22Pyroclastic+Flow%22+%2D+Day+17+%2D+Advent+of+Code+2022+%23AdventOfCode+https%3A%2F%2Fadventofcode%2Ecom%2F2022%2Fday%2F17'}else{return false;}" target="_blank">Mastodon</a
+></span>]</span> this puzzle.</p>
+</main>
+
+<!-- ga -->
+<script>
+(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
+(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
+m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
+})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
+ga('create', 'UA-69522494-1', 'auto');
+ga('set', 'anonymizeIp', true);
+ga('send', 'pageview');
+</script>
+<!-- /ga -->
+</body>
+</html>
\ No newline at end of file