This commit is contained in:
Paul-Henri Froidmont 2023-12-07 15:55:01 +01:00
parent 6e5bb0fffe
commit 426f64709f
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 1110 additions and 0 deletions

1000
input/day07 Normal file

File diff suppressed because it is too large Load diff

110
src/day07.scala Normal file
View file

@ -0,0 +1,110 @@
package aoc
package day07
import util.chaining.*
import math.Ordering.Implicits.seqOrdering
val dayNumber = "07"
@main def part1: Unit =
println(part1(loadInput(dayNumber)))
@main def part2: Unit =
println(part2(loadInput(dayNumber)))
type Card = Char
enum HandType:
case FiveOfAKind,
FourOfAKind,
FullHouse,
ThreeOfAKind,
TwoPair,
OnePair,
HighCard
given Ordering[HandType] = Ordering.by(_.ordinal)
def part1(input: String): String =
val cardsOrder = "AKQJT98765432"
given Ordering[Card] = Ordering.by(cardsOrder.indexOf(_))
final case class Hand(cards: Seq[Card], bid: Long):
val tpe =
cards
.groupMapReduce(identity)(_ => 1)(_ + _)
.values
.toSeq
.sorted
.reverse match
case 5 :: _ => HandType.FiveOfAKind
case 4 :: _ => HandType.FourOfAKind
case 3 :: 2 :: _ => HandType.FullHouse
case 3 :: _ => HandType.ThreeOfAKind
case 2 :: 2 :: _ => HandType.TwoPair
case 2 :: _ => HandType.OnePair
case _ => HandType.HighCard
object Hand:
given Ordering[Hand] =
Ordering
.by[Hand, HandType](_.tpe)
.orElseBy[Seq[Card]](_.cards)
input
.split('\n')
.map(_.split(' ') match
case Array(cards, bid) => Hand(cards.toSeq, bid.toLong)
)
.sorted
.map(_.bid)
.reverse
.zipWithIndex
.map((bid, index) => bid * (index + 1))
.sum
.toString
def part2(input: String): String =
val cardsOrder = "AKQT98765432J"
given Ordering[Card] = Ordering.by(cardsOrder.indexOf(_))
final case class Hand(cards: Seq[Card], bid: Long):
val jCount = cards.count(_ == 'J')
val tpe =
cards
.groupMapReduce(identity)(_ => 1)(_ + _)
.values
.toSeq
.sorted
.reverse match
case 5 :: _ => HandType.FiveOfAKind
case 4 :: _ if jCount == 4 => HandType.FiveOfAKind
case 4 :: _ if jCount == 1 => HandType.FiveOfAKind
case 4 :: _ => HandType.FourOfAKind
case 3 :: 2 :: _ if jCount == 3 => HandType.FiveOfAKind
case 3 :: 2 :: _ if jCount == 2 => HandType.FiveOfAKind
case 3 :: 2 :: _ => HandType.FullHouse
case 3 :: _ if jCount == 3 => HandType.FourOfAKind
case 3 :: _ if jCount == 1 => HandType.FourOfAKind
case 3 :: _ => HandType.ThreeOfAKind
case 2 :: 2 :: _ if jCount == 2 => HandType.FourOfAKind
case 2 :: 2 :: _ if jCount == 1 => HandType.FullHouse
case 2 :: 2 :: _ => HandType.TwoPair
case 2 :: _ if jCount == 2 => HandType.ThreeOfAKind
case 2 :: _ if jCount == 1 => HandType.ThreeOfAKind
case 2 :: _ => HandType.OnePair
case _ if jCount == 1 => HandType.OnePair
case _ => HandType.HighCard
object Hand:
given Ordering[Hand] =
Ordering
.by[Hand, HandType](_.tpe)
.orElseBy(_.cards)
input
.split('\n')
.map(_.split(' ') match
case Array(cards, bid) => Hand(cards.toSeq, bid.toLong)
)
.sorted
.reverse
.zipWithIndex
.map((hand, index) => hand.bid * (index + 1))
.sum
.toString