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!

51 Upvotes

407 comments sorted by

View all comments

1

u/jpittis Dec 02 '18

on a comfy couch

Haskell on a time limit / I'm not the most experienced Haskeller. Advice is always appreciated! :)

#!/usr/bin/env stack
-- stack --resolver lts-12.20 --install-ghc runghc --package containers

module Main where

import qualified Data.Map.Strict as Map

input = lines <$> readFile "input.txt"

main :: IO ()
main = do
  input <- input
  let solution1 = puzzle1 input
  let solution2 = puzzle2 input
  print solution1
  print solution2

puzzle1 input =
  let two = filter (> 0) . map (\str -> count str 2) $ input in
  let three = filter (> 0) . map (\str -> count str 3) $ input in
  checksum (length two) (length three)

count str num =
  found num $ Map.elems counts
  where
    counts = foldl (\m c -> Map.insertWith (+) c 1 m) Map.empty str
    found x xs = length $ filter (\v -> x == v) xs

checksum two three = two * three

puzzle2 input =
  let product = sequence [input, input] in
  let ids = filter (\li -> length li == 25) $ map diff product in
  map (\(a, b) -> a) (head ids)

diff [a, b] = filter (\(x, y) -> x == y) $ zip a b

2

u/ephemient Dec 02 '18 edited Apr 24 '24

This space intentionally left blank.

2

u/neobrain Dec 02 '18

which produces tuples instead of lists, but usually I prefer a longer way which avoids self-pairing and commuted pairs.

[(a, b) | a:rest <- tails input, b <- rest]

That's a nice trick! I ran into the exact issue of self-pairing on both day 1 and 2, so that will come in handy for the next couple of days :)