Created
December 3, 2022 21:43
-
-
Save hovsater/572840bf173a3a55f04099ae96b26571 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 2022, Day 3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Day03 exposing (partOne, partTwo) | |
import Set exposing (Set) | |
type alias ItemType = | |
Char | |
itemTypePriority : ItemType -> Int | |
itemTypePriority itemType = | |
if Char.isLower itemType then | |
Char.toCode itemType - Char.toCode 'a' + 1 | |
else | |
Char.toCode itemType - Char.toCode 'A' + 26 + 1 | |
type alias Compartment = | |
Set ItemType | |
type alias Rucksack = | |
List ItemType | |
toCompartments : Rucksack -> ( Compartment, Compartment ) | |
toCompartments rucksack = | |
let | |
middle : Int | |
middle = | |
List.length rucksack // 2 | |
in | |
( List.take middle rucksack, List.drop middle rucksack ) | |
|> Tuple.mapBoth Set.fromList Set.fromList | |
parseInput : String -> List Rucksack | |
parseInput input = | |
input | |
|> String.lines | |
|> List.map String.toList | |
partOne : String -> Int | |
partOne input = | |
let | |
findCommonItemType : ( Compartment, Compartment ) -> Maybe ItemType | |
findCommonItemType ( c1, c2 ) = | |
Set.intersect c1 c2 |> Set.toList |> List.head | |
in | |
input | |
|> parseInput | |
|> List.filterMap (toCompartments >> findCommonItemType) | |
|> List.map itemTypePriority | |
|> List.sum | |
partTwo : String -> Int | |
partTwo input = | |
let | |
groupsOf : Int -> List a -> List (List a) | |
groupsOf n list = | |
case list of | |
[] -> | |
[] | |
_ -> | |
List.take n list :: groupsOf n (List.drop n list) | |
findCommonItemType : List Rucksack -> Maybe ItemType | |
findCommonItemType rucksacks = | |
case List.map Set.fromList rucksacks of | |
[ c1, c2, c3 ] -> | |
Set.intersect c1 c2 |> Set.intersect c3 |> Set.toList |> List.head | |
_ -> | |
Nothing | |
in | |
input | |
|> parseInput | |
|> groupsOf 3 | |
|> List.filterMap findCommonItemType | |
|> List.map itemTypePriority | |
|> List.sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment