Skip to content

Instantly share code, notes, and snippets.

@needToRoll
Last active December 11, 2023 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save needToRoll/0ee8da5847c6b582264425b498c4b728 to your computer and use it in GitHub Desktop.
Save needToRoll/0ee8da5847c6b582264425b498c4b728 to your computer and use it in GitHub Desktop.
import kotlin.math.pow
fun main(args: Array<String>) {
println(solveDay07Part1("07.txt"))
println(solveDay07Part2("07.txt"))
}
val DECK_OF_CARDS = setOf(
'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'
)
fun solveDay07Part1(filename: String): Long {
var sum = 0L
val lines = FileUtils.readFromClasspath(filename)
val bids = lines.map { it.split(" ") }
.map { Bid(it[0].trim(), it[1].trim().toInt()) }
var sorted = bids.sorted()
for ((i, bid) in sorted.withIndex()) {
sum += (i + 1) * bid.amount
}
return sum
}
fun solveDay07Part2(filename: String): Int {
val lines = FileUtils.readFromClasspath(filename)
//TODO: Implement
return -1
}
data class Bid(val cards: String, val amount: Int) : Comparable<Bid> {
fun cardValueByPosition(): Long {
var sum = 0L
for ((i, c) in cards.withIndex()) {
// println("Value of $c is ${DECK_OF_CARDS.indexOf(c)}")
val value = 10.toDouble().pow(cards.length - i - 1) * (DECK_OF_CARDS.indexOf(c) + 2)
// println(value)
sum += value.toLong()
}
return sum
}
fun detectHand(): Hands {
val groupedCards = cards.toCharArray()
.groupBy { DECK_OF_CARDS.indexOf(it) }
val hand = when {
groupedCards.size == 1 ->
Hands.FIVE_OF_A_KIND
groupedCards.any { it.value.size == 4 } ->
Hands.FOUR_OF_A_KIND
groupedCards.size == 2 ->
Hands.FULL_HOSE
groupedCards.any { it.value.size == 3 } ->
Hands.THREE_OF_A_KIND
groupedCards.filter { it.value.size == 2 }.count() == 2 ->
Hands.TWO_PAIRS
groupedCards.any { it.value.size == 2 } ->
Hands.PAIR
else ->
Hands.HIGH_CARD
}
return hand;
}
override fun compareTo(other: Bid): Int {
return compareBy<Bid>({ it.detectHand() }, { it.cardValueByPosition() }).compare(this, other)
}
}
enum class Hands {
HIGH_CARD, PAIR, TWO_PAIRS, THREE_OF_A_KIND, FULL_HOSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment