r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


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

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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!

48 Upvotes

407 comments sorted by

View all comments

1

u/NeilNjae Dec 02 '18

Haskell. For once, not using libraries was easier! (Tidyied a bit, using suggestions from this thread to use intersect and the fancy-pants list comprehension.)

Also on Github

import Data.List

main :: IO ()
main = do 
        text <- readFile "data/advent02.txt"
        let ids = lines text
        print $ part1 ids
        putStrLn $ part2 ids

part1 ids = (fst counts23) * (snd counts23)
    where allLetterCounts = map letterCounts ids
          counts23 = foldl' addCounts (0, 0) allLetterCounts

letterCounts :: String -> [Int]
letterCounts = map length . group . sort

addCounts :: (Int, Int) -> [Int] -> (Int, Int)
addCounts (twos, threes) counts = (twos', threes')
    where twos'   = if 2 `elem` counts then twos + 1   else twos
          threes' = if 3 `elem` counts then threes + 1 else threes

part2 ids = uncurry intersect closeIds
    where closeIds = head $ filter (\ab -> uncurry differenceCount ab == 1) 
                        [(a, b) | a:rest <- tails ids, b <- rest]

differenceCount :: String -> String -> Int
differenceCount this that = length $ filter (\(a, b) -> a /= b) $ zip this that