File tree Expand file tree Collapse file tree 3 files changed +39
-6
lines changed
main/kotlin/de/ronny_h/aoc
test/kotlin/de/ronny_h/aoc/extensions Expand file tree Collapse file tree 3 files changed +39
-6
lines changed Original file line number Diff line number Diff line change @@ -21,3 +21,23 @@ fun Long.digitCount(): Int {
2121 * Returns the ones digit (the rightmost digit) of the given Long number.
2222 */
2323fun 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+ }
Original file line number Diff line number Diff line change 11package de.ronny_h.aoc.year24.day24
22
33import de.ronny_h.aoc.AdventOfCode
4+ import de.ronny_h.aoc.extensions.toDigit
45
56fun 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) }
Original file line number Diff line number Diff line change 11package de.ronny_h.aoc.extensions
22
3+ import io.kotest.assertions.throwables.shouldThrow
34import io.kotest.core.spec.style.StringSpec
45import io.kotest.data.forAll
56import 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})
You can’t perform that action at this time.
0 commit comments