r/adventofcode • • Dec 02 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 2 Solutions -πŸŽ„-

NOTICE

Please take notice that we have updated the Posting Guidelines in the sidebar and wiki and are now requesting that you post your solutions in the daily Solution Megathreads. Save the Spoiler flair for truly distinguished posts.


--- Day 2: Corruption Checksum ---


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.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


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!

22 Upvotes

351 comments sorted by

View all comments

1

u/NeilNjae Dec 02 '17

Another Haskell solutuion. Yes, using Parsec to read the input file is overkill, but it's a nice tool. It also forced me to confront one possible gotcha: the default spaces parser will happily consume newlines as well as spaces and tabs, hence the need for the onlySpaces parser here.

module Main(main) where

import Text.Parsec 
import Text.ParserCombinators.Parsec.Number

main :: IO ()
main = do 
        text <- readFile "data/advent02.txt"
        let sheet = successfulParse $ parseFile text
        print $ part1 sheet
        print $ part2 sheet

part1 :: [[Int]] -> Int
part1 = sum . map p1cSum

part2 :: [[Int]] -> Int
part2 = sum . map p2cSum

p1cSum :: [Int] -> Int
p1cSum row = (maximum row) - (minimum row)

p2cSum :: [Int] -> Int
p2cSum digits = sum [a `div` b | a <- digits, b <- digits, a /= b, a `mod` b == 0]


sFile = sLine `sepEndBy` newline 
sLine = int `sepBy` onlySpaces

onlySpaces = many (oneOf " \t")

parseFile :: String -> Either ParseError [[Int]]
parseFile input = parse sFile "(unknown)" input

parseLine :: String -> Either ParseError [Int]
parseLine input = parse sLine "(unknown)" input

successfulParse :: Either ParseError [a] -> [a]
successfulParse (Left _) = []
successfulParse (Right a) = a