Day 8: Playground

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

  • Amy@piefed.blahaj.zone
    link
    fedilink
    English
    arrow-up
    5
    ·
    edit-2
    1 month ago

    Haskell

    They’re getting interesting now!

    import Control.Monad  
    import Data.List  
    import Data.List.Split  
    import Data.Ord  
    import Data.Set qualified as Set  
    
    readPos = (\([x, y, z] :: [Int]) -> (x, y, z)) . map read . splitOn ","  
    
    pairs = init . tails >=> (\(x : xs) -> map (x,) xs)  
    
    dist (x1, y1, z1) (x2, y2, z2) =  
      (x2 - x1) ^ 2 + (y2 - y1) ^ 2 + (z2 - z1) ^ 2  
    
    connect circuits (a, b) =  
      let (joined, rest) =  
            partition (\c -> a `Set.member` c || b `Set.member` c) circuits  
       in Set.unions joined : rest  
    
    main = do  
      boxes <- map readPos . lines <$> readFile "input08"  
      let steps =  
            (zip <*> tail . scanl' connect (map Set.singleton boxes)) $  
              sortOn (uncurry dist) (pairs boxes)  
      print . product . take 3 . sortOn Down . map Set.size $  
        (snd . last . take 1000 $ steps)  
      let Just (((x1, _, _), (x2, _, _)), _) =  
            find ((== 1) . length . snd) steps  
       in print $ x1 * x2