🍪 - 2023 DAY 7 SOLUTIONS -🍪 - eviltoast

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

  • cvttsd2si@programming.dev
    link
    fedilink
    arrow-up
    3
    ·
    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)