Skip to content

Commit 4c9502f

Browse files
committed
Day 2
1 parent 48f52fb commit 4c9502f

2 files changed

Lines changed: 104 additions & 0 deletions

File tree

src/main/kotlin/y25/Day2.kt

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package y25
2+
3+
import common.puzzle.solvePuzzle
4+
import common.puzzle.Input
5+
import common.puzzle.Puzzle
6+
import common.datastructures.*
7+
import common.ext.*
8+
import common.util.*
9+
import java.util.*
10+
import kotlin.math.*
11+
import kotlin.system.exitProcess
12+
13+
14+
fun main() = solvePuzzle(year = 2025, day = 2) { Day2(it) }
15+
16+
class Day2(val input: Input) : Puzzle {
17+
data class Range(val start: Long, val end: Long)
18+
19+
private val ranges = input.string.split(",").map { range ->
20+
val (start, end) = range.split("-")
21+
Range(start.toLong(), end.toLong())
22+
}
23+
24+
private fun Range.invalidIds(): List<Long> {
25+
val invalidIds = mutableListOf<Long>()
26+
var half = start.toString(10).let { str ->
27+
val halfLen = str.length / 2
28+
if (halfLen > 0) {
29+
str.take(halfLen)
30+
} else {
31+
"0"
32+
}
33+
}
34+
while (true) {
35+
val full = "$half$half".toLong()
36+
if (full > end) {
37+
return invalidIds
38+
}
39+
if (full >= start) {
40+
invalidIds.add(full)
41+
}
42+
half = (half.toLong() + 1).toString()
43+
}
44+
}
45+
46+
private fun Range.invalidIds2(): Set<Long> {
47+
val invalidIds = mutableSetOf<Long>()
48+
var base = "1"
49+
while (true) {
50+
var sequence = "$base$base"
51+
if (sequence.toLong() > end) {
52+
return invalidIds
53+
}
54+
55+
while (true) {
56+
val longValue = sequence.toLong()
57+
if (longValue > end) {
58+
break
59+
}
60+
if (longValue >= start) {
61+
invalidIds += longValue
62+
}
63+
sequence += base
64+
}
65+
66+
base = (base.toLong() + 1).toString()
67+
}
68+
}
69+
70+
override fun solveLevel1(): Any {
71+
return ranges.sumOf { range ->
72+
range.invalidIds().sum()
73+
}
74+
}
75+
76+
override fun solveLevel2(): Any {
77+
return ranges.sumOf { range ->
78+
range.invalidIds2().sum()
79+
}
80+
}
81+
}

src/test/kotlin/y25/Day2Test.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package y25
2+
3+
import common.puzzle.Input
4+
import org.junit.jupiter.api.Assertions.assertEquals
5+
import org.junit.jupiter.api.Test
6+
7+
internal class Day2Test {
8+
private val sample = Input("""
9+
11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124
10+
""".trimIndent())
11+
12+
private val day = Day2(sample)
13+
14+
@Test
15+
fun solveLevel1() {
16+
assertEquals(1227775554L, day.solveLevel1())
17+
}
18+
19+
@Test
20+
fun solveLevel2() {
21+
assertEquals(4174379265L, day.solveLevel2())
22+
}
23+
}

0 commit comments

Comments
 (0)