|
| 1 | +package com.matsemann.adventofcode2023 |
| 2 | + |
| 3 | +import com.matsemann.adventofcode2023.utils.* |
| 4 | + |
| 5 | +fun day07_1(lines: List<String>): Any { |
| 6 | + return lines.map { line -> |
| 7 | + val parts = line.split(" ") |
| 8 | + val cards = parts[0].toList().map { |
| 9 | + when (it) { |
| 10 | + 'T' -> 'A' |
| 11 | + 'J' -> 'B' |
| 12 | + 'Q' -> 'C' |
| 13 | + 'K' -> 'D' |
| 14 | + 'A' -> 'E' |
| 15 | + else -> it |
| 16 | + } |
| 17 | + } |
| 18 | + cards to parts[1].toInt() |
| 19 | + } |
| 20 | + .sortedWith(compareBy({ (hand, _) -> |
| 21 | + val pairs = hand.groupBy { it }.values.map { it.size }.sortedDescending() |
| 22 | + |
| 23 | + when { |
| 24 | + pairs[0] == 5 -> 7 |
| 25 | + pairs[0] == 4 -> 6 |
| 26 | + pairs[0] == 3 && pairs[1] == 2 -> 5 |
| 27 | + pairs[0] == 3 -> 4 |
| 28 | + pairs[0] == 2 && pairs[1] == 2 -> 3 |
| 29 | + pairs[0] == 2 -> 2 |
| 30 | + else -> 1 |
| 31 | + } |
| 32 | + }, { (hand, _) -> hand.toString() })) |
| 33 | + .mapIndexed { i, (cards, bet) -> |
| 34 | + bet * (i + 1) |
| 35 | + }.sum() |
| 36 | +} |
| 37 | + |
| 38 | + |
| 39 | +fun day07_2(lines: List<String>): Any { |
| 40 | + return lines.map { line -> |
| 41 | + val parts = line.split(" ") |
| 42 | + val cards = parts[0].toList().map { |
| 43 | + when (it) { |
| 44 | + 'T' -> 'A' |
| 45 | + 'J' -> '0' |
| 46 | + 'Q' -> 'C' |
| 47 | + 'K' -> 'D' |
| 48 | + 'A' -> 'E' |
| 49 | + else -> it |
| 50 | + } |
| 51 | + } |
| 52 | + cards to parts[1].toInt() |
| 53 | + } |
| 54 | + .sortedWith(compareBy({ (hand, _) -> |
| 55 | + val jokers = hand.count { it == '0' } |
| 56 | + val pairs = hand.filter { it != '0' }.groupBy { it }.values.map { it.size }.sortedDescending() |
| 57 | + |
| 58 | + when { |
| 59 | + jokers == 5 || pairs[0] + jokers == 5 -> 7 |
| 60 | + pairs[0] + jokers == 4 -> 6 |
| 61 | + pairs[0] + jokers == 3 && pairs[1] == 2 -> 5 |
| 62 | + pairs[0] + jokers == 3 -> 4 |
| 63 | + pairs[0] + jokers == 2 && pairs[1] == 2 -> 3 |
| 64 | + pairs[0] + jokers == 2 -> 2 |
| 65 | + else -> 1 |
| 66 | + } |
| 67 | + }, { (hand, _) -> hand.toString() })) |
| 68 | + .mapIndexed { i, (cards, bet) -> |
| 69 | + bet * (i + 1) |
| 70 | + }.sum() |
| 71 | +} |
| 72 | + |
| 73 | +fun main() { |
| 74 | + |
| 75 | +// run("1", fileName = "day07_ex.txt", func = ::day07_1) |
| 76 | + run("2", fileName = "day07_ex.txt", func = ::day07_2) |
| 77 | + |
| 78 | +// 249620106 |
| 79 | +// run("1", fileName = "day07.txt", func = ::day07_1) |
| 80 | + run("2", fileName = "day07.txt", func = ::day07_2) |
| 81 | +} |
0 commit comments