1
0
Fork 0

solve 2022 day 3 pt 1 & 2

This commit is contained in:
Sloane Perrault 2022-12-04 08:33:19 -05:00
parent 47a2d18e2f
commit 0d8293833f
5 changed files with 42 additions and 1 deletions

View file

@ -2,7 +2,7 @@
| S | M | T | W | T | F | S |
| :-: | :-: | :-: | :-: | :-: | :-: | :--: |
| | | | | [1] | [2] | 3 |
| | | | | [1] | [2] | [3] |
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
@ -10,3 +10,4 @@
[1]: ./src/Aoc/Day1.hs
[2]: ./src/Aoc/Day2.hs
[3]: ./src/Aoc/Day3.hs

View file

@ -27,6 +27,7 @@ library
exposed-modules:
Aoc.Day1
Aoc.Day2
Aoc.Day3
other-modules:
Paths_aoc
hs-source-dirs:
@ -34,6 +35,8 @@ library
ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints
build-depends:
base >=4.7 && <5
, containers
, split
, text
default-language: Haskell2010
@ -47,6 +50,8 @@ executable aoc-exe
build-depends:
aoc
, base >=4.7 && <5
, containers
, split
, text
default-language: Haskell2010
@ -61,5 +66,7 @@ test-suite aoc-test
build-depends:
aoc
, base >=4.7 && <5
, containers
, split
, text
default-language: Haskell2010

View file

@ -4,6 +4,7 @@ module Main (main) where
import System.Environment (getArgs)
import qualified Aoc.Day1
import qualified Aoc.Day2
import qualified Aoc.Day3
main :: IO ()
main = do
@ -15,6 +16,7 @@ main = do
let f = case day of 1 -> Aoc.Day1.solve
2 -> Aoc.Day2.solve
3 -> Aoc.Day3.solve
_ -> error "unknown day"
putStrLn $ show $ f part contents

View file

@ -22,6 +22,8 @@ description: Please see the README on GitHub at <https://github.com/sloa
dependencies:
- base >= 4.7 && < 5
- text
- containers
- split
ghc-options:
- -Wall

29
2022/src/Aoc/Day3.hs Normal file
View file

@ -0,0 +1,29 @@
module Aoc.Day3 (solve, halve, shared, charToInt) where
import Data.Char
import qualified Data.Set as Set
import Data.List.Split (chunksOf)
halve :: String -> [String]
halve xs = [front, back]
where
midpoint = length xs `div` 2
front = take midpoint xs
back = drop midpoint xs
shared :: [String] -> String
shared xs = Set.toList $ foldr1 Set.intersection $ map Set.fromList xs
charToInt :: Char -> Int
charToInt c
| 'a' <= c && c <= 'z' = ord c - ord 'a' + 1
| 'A' <= c && c <= 'Z' = ord c - ord 'A' + 27
| otherwise = -1
solve :: Integer -> String -> Integer
solve 1 input = sum $ map (toInteger . charToInt . head . shared . halve) $ lines input
solve 2 input = sum $ map (toInteger . charToInt . head . shared) $ chunksOf 3 $ lines input
solve _ _ = 0