Skip to content

Commit 06c175c

Browse files
committed
Add 2023 Day 13 Part 2 solution
1 parent 6970300 commit 06c175c

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

adventofcode2023/Day13.kt

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,37 +11,44 @@ object Day13 {
1111
private fun verticalLine(list: List<String>, index: Int): String =
1212
list.joinToString(separator = "") { it[index].toString() }
1313

14-
private fun checkIfSameLines(list: List<String>, a: Int, b: Int, vertical: Boolean): Boolean
15-
= (vertical && verticalLine(list, a) == verticalLine(list, b)) || (!vertical && list[a] == list[b])
14+
private fun countLinesDifference(list: List<String>, a: Int, b: Int, vertical: Boolean): Int {
15+
val lineA = if (vertical) verticalLine(list, a) else list[a]
16+
val lineB = if (vertical) verticalLine(list, b) else list[b]
17+
return lineA.withIndex().count { it.value != lineB[it.index] }
18+
}
1619

17-
private fun findReflectionLine(list: List<String>, vertical: Boolean = false): Int? {
20+
private fun findReflectionLine(
21+
list: List<String>,
22+
different: Int = 0,
23+
vertical: Boolean = false
24+
): Int? {
1825
val maxIndex = if (vertical) list[0].length else list.size
26+
1927
for (i in 0..maxIndex - 2) {
20-
if (checkIfSameLines(list, i, i + 1, vertical)) {
21-
var j = 1
22-
var isReflection = true
23-
24-
while (i - j >= 0 && i + j + 1 < maxIndex) {
25-
if (!checkIfSameLines(list, i - j, i + j + 1, vertical)) {
26-
isReflection = false
27-
break
28-
}
29-
j++
30-
}
31-
32-
if (isReflection) return i + 1
28+
var j = 1
29+
var differentCount = countLinesDifference(list, i, i + 1, vertical)
30+
31+
while (differentCount <= different && i - j >= 0 && i + j + 1 < maxIndex) {
32+
differentCount += countLinesDifference(list, i - j, i + j + 1, vertical)
33+
j++
3334
}
35+
36+
if (differentCount == different) return i + 1
3437
}
3538

3639
return null
3740
}
3841

3942
fun part1() = println(inputs.sumOf {
40-
val ind = (findReflectionLine(it, true) ?: findReflectionLine(it)?.times(100))
41-
ind!!.toInt()
43+
(findReflectionLine(it, vertical = true) ?: findReflectionLine(it)?.times(100))!!.toInt()
44+
})
45+
46+
fun part2() = println(inputs.sumOf {
47+
(findReflectionLine(it, 1, vertical = true) ?: findReflectionLine(it, 1)?.times(100))!!.toInt()
4248
})
4349
}
4450

4551
fun main() {
4652
Day13.part1()
53+
Day13.part2()
4754
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy