Skip to content

Commit a0a6988

Browse files
committed
Factor out functions for converting a Digit to Boolean and vice versa
1 parent e0e7fb4 commit a0a6988

File tree

3 files changed

+39
-6
lines changed

3 files changed

+39
-6
lines changed

src/main/kotlin/de/ronny_h/aoc/extensions/Digits.kt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,23 @@ fun Long.digitCount(): Int {
2121
* Returns the ones digit (the rightmost digit) of the given Long number.
2222
*/
2323
fun Long.onesDigit(): Int = abs(this % 10).toInt()
24+
25+
/**
26+
* Converts a digit character to a boolean value.
27+
* @return `true` if this is '1', `false` if this is '0'.
28+
* @throws IllegalStateException if this is neither '1' nor '0'.
29+
*/
30+
fun Char.toBoolean(): Boolean = when (this) {
31+
'1' -> true
32+
'0' -> false
33+
else -> error("must be either 0 or 1: '$this'")
34+
}
35+
36+
/**
37+
* Converts a boolean value to a digit character as String.
38+
* @return "1" if this is `true`, "0" otherwise.
39+
*/
40+
fun Boolean.toDigit(): String = when (this) {
41+
true -> "1"
42+
false -> "0"
43+
}

src/main/kotlin/de/ronny_h/aoc/year24/day24/CrossedWires.kt

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package de.ronny_h.aoc.year24.day24
22

33
import de.ronny_h.aoc.AdventOfCode
4+
import de.ronny_h.aoc.extensions.toDigit
45

56
fun main() = CrossedWires().run(66055249060558, 0)
67

@@ -59,12 +60,7 @@ class CrossedWires: AdventOfCode<Long>(2024, 24) {
5960
.toLong(2)
6061

6162
private fun Map<String, Wire>.withPrefixAsBinary(prefix: String): String = withPrefixSortedByLSBFirst(prefix)
62-
.joinToString("") {
63-
when (it.value) {
64-
true -> "1"
65-
false -> "0"
66-
}
67-
}
63+
.joinToString("") { it.value.toDigit() }
6864

6965
private fun Map<String, Wire>.withPrefixSortedByLSBFirst(prefix: String): List<Wire> = values
7066
.filter { it.name.startsWith(prefix) }

src/test/kotlin/de/ronny_h/aoc/extensions/DigitsTest.kt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package de.ronny_h.aoc.extensions
22

3+
import io.kotest.assertions.throwables.shouldThrow
34
import io.kotest.core.spec.style.StringSpec
45
import io.kotest.data.forAll
56
import io.kotest.data.row
@@ -29,4 +30,20 @@ class DigitsTest : StringSpec({
2930
number.onesDigit() shouldBe ones
3031
}
3132
}
33+
34+
"toBoolean converts a char digit to Boolean" {
35+
'0'.toBoolean() shouldBe false
36+
'1'.toBoolean() shouldBe true
37+
}
38+
39+
"toBoolean throws an Exception for illegal digits" {
40+
shouldThrow<IllegalStateException> {
41+
'2'.toBoolean()
42+
}
43+
}
44+
45+
"toDigit converts a Boolean to a digit String" {
46+
true.toDigit() shouldBe "1"
47+
false.toDigit() shouldBe "0"
48+
}
3249
})

0 commit comments

Comments
 (0)