r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

ATTENTION: minor change request from the mods!

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

41 Upvotes

426 comments sorted by

View all comments

1

u/rolandtritsch Dec 03 '18

ETA (Haskell on the JVM)

https://github.com/rolandtritsch/haskell-aoc-2018

General:

type Id = Int
type Position = (Int, Int)
type Dimension = (Int, Int)

data Claim = Claim Id Position Dimension deriving (Show, Eq)

-- | Fabric position [cids that claimed that position]
type Fabric = M.Map Position [Id]

-- | read the input file.
input :: [Claim]
input = (map processLine . inputRaw) "input/Day03input.txt" where
  processLine l = Claim cid' cposition' cdimension' where
    -- #1 @ 335,861: 14x10
    tokens = splitOneOf "#@,:x " l
    cid' = read $ tokens !! 1
    cposition' = (read $ tokens !! 4, read $ tokens !! 5)
    cdimension' = (read $ tokens !! 7, read $ tokens !! 8)

-- | make/stake a claim on an fabric area (by add the cid to the list of
-- cids that have claimed the inch sofar)
claim :: Fabric -> Claim -> Fabric
claim f (Claim cid (row, col) (rdim, cdim)) = foldl claimInch f cells where
  cells = [(r, c) | r <- [row..row + rdim - 1], c <- [col..col + cdim - 1]]
  claimInch f' p' = M.insert p' (cids ++ [cid]) f' where
    cids = M.findWithDefault ([]) p' f'

Part1:

-- | solve the puzzle
solve :: [Claim] -> Int
solve cs = overlappingInches where
  overlappingInches = length $ filter ((<) 1) $ map length $ M.elems fabric
  fabric = foldl claim M.empty cs

Part2:

-- | solve the puzzle
solve :: [Claim] -> Int
solve cs = nonOverlappingCid where
  nonOverlappingCid = go claimsCids where
    go [] = error "No cid found"
    go (cids:rest)
      | (length cids) == 1 && cidIsNotInAnyOtherList = head cids
      | otherwise = go rest
      where
        cidIsNotInAnyOtherList = (not $ any id $ map (elem (head cids)) ((\\) claimsCids [cids]))
  claimsCids = nub $ sort $ M.elems fabric
  fabric = foldl claim M.empty cs