this post was submitted on 07 Dec 2023
18 points (100.0% liked)

Advent Of Code

770 readers
1 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
18
submitted 11 months ago* (last edited 11 months ago) by Ategon to c/advent_of_code
 

Day 7: Camel Cards

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


๐Ÿ”’ Thread is locked until there's at least 100 2 star entries on the global leaderboard

๐Ÿ”“ Thread has been unlocked after around 20 mins

you are viewing a single comment's thread
view the rest of the comments
[โ€“] cvttsd2si 3 points 11 months ago

Scala3

val tiers = List(List(1, 1, 1, 1, 1), List(1, 1, 1, 2), List(1, 2, 2), List(1, 1, 3), List(2, 3), List(1, 4), List(5))
val cards = List('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')

def cardValue(base: Long, a: List[Char], cards: List[Char]): Long =
    a.foldLeft(base)(cards.size * _ + cards.indexOf(_))

def hand(a: List[Char]): List[Int] =
    a.groupMapReduce(s => s)(_ => 1)(_ + _).values.toList.sorted

def power(a: List[Char]): Long =
  cardValue(tiers.indexOf(hand(a)), a, cards)

def power3(a: List[Char]): Long = 
  val x = hand(a.filter(_ != 'J'))
  val t = tiers.lastIndexWhere(x.zipAll(_, 0, 0).forall(_ <= _))
  cardValue(t, a, 'J'::cards)

def win(a: List[String], pow: List[Char] => Long) =
    a.flatMap{case s"$hand $bid" => Some((pow(hand.toList), bid.toLong)); case _ => None}
        .sorted.map(_._2).zipWithIndex.map(_ * _.+(1)).sum

def task1(a: List[String]): Long = win(a, power)
def task2(a: List[String]): Long = win(a, power3)