Skip to content

Instantly share code, notes, and snippets.

@hovsater
Created December 3, 2022 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hovsater/572840bf173a3a55f04099ae96b26571 to your computer and use it in GitHub Desktop.
Save hovsater/572840bf173a3a55f04099ae96b26571 to your computer and use it in GitHub Desktop.
Solution to Advent of Code 2022, Day 3.
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