Advertisement
hrabrica

AoC | Day 7 | Part 1

Dec 7th, 2023
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.03 KB | Source Code | 0 0
  1. package year_2023.day_7
  2.  
  3. fun partOne() {
  4.     println("[2023] Day seven, part one...")
  5.  
  6.     val cardsByValue = listOf("A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2").reversed()
  7.     val handBidPairs = input().split("\n")
  8.         .map { it.trim() }
  9.         .map {
  10.             it.split(" ")[0].trim() to
  11.                     it.split(" ")[1].toInt()
  12.         }
  13.  
  14.     fun getHandValue(hand: List<String>): Int {
  15.         return when {
  16.             hand.count { it == hand[0] } == 5 -> 10
  17.             hand.any { char -> hand.count { it == char } == 4 } -> 9
  18.             hand.any { char -> hand.count { it == char } == 3 } && hand.toSet().size == 2 -> 8
  19.             hand.any { char -> hand.count { it == char } == 3 } -> 7
  20.             hand.any { char -> hand.count { it == char } == 2 } && hand.toSet().size == 3 -> 6
  21.             hand.any { char -> hand.count { it == char } == 2 } && hand.toSet().size == 4 -> 5
  22.             else -> 0
  23.         }
  24.     }
  25.  
  26.    val comparator = Comparator<Pair<String, Int>> { (hand1, _), (hand2, _) ->
  27.        val hand1Cards = hand1.split("").filter { it.isNotBlank() }
  28.        val hand2Cards = hand2.split("").filter { it.isNotBlank() }
  29.        val hand1Value = getHandValue(hand1Cards)
  30.        val hand2Value = getHandValue(hand2Cards)
  31.  
  32.        if (hand1Value > hand2Value) {
  33.            return@Comparator 1
  34.        }
  35.        if (hand1Value < hand2Value) {
  36.            return@Comparator -1
  37.        }
  38.  
  39.        repeat(hand1Cards.size) { idx ->
  40.            if (cardsByValue.indexOf(hand1Cards[idx]) > cardsByValue.indexOf(hand2Cards[idx])) {
  41.                return@Comparator 1
  42.            }
  43.  
  44.            if (cardsByValue.indexOf(hand1Cards[idx]) < cardsByValue.indexOf(hand2Cards[idx])) {
  45.                return@Comparator -1
  46.            }
  47.        }
  48.  
  49.        println("Shouldn't happen")
  50.        0
  51.    }
  52.  
  53.     val sortedHandBidPairs = handBidPairs.sortedWith(comparator)
  54.     var sum = 0
  55.     sortedHandBidPairs.forEachIndexed { index, (_, bid) ->
  56.         sum += (index + 1) * bid
  57.     }
  58.  
  59.     println(sum)
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement