Skip to content

Commit 8ab2a82

Browse files
committed
Day 13
1 parent e9d2c05 commit 8ab2a82

File tree

3 files changed

+933
-0
lines changed

3 files changed

+933
-0
lines changed

src/day13/Day13.kt

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package day13
2+
3+
import utils.verify
4+
import java.io.File
5+
6+
/** https://adventofcode.com/2021/day/13 */
7+
8+
fun main() {
9+
10+
data class Fold(val x: Boolean, val pos: Int)
11+
12+
class Data(lines: List<String>) {
13+
private val matrix: Array<BooleanArray>
14+
private val folds: ArrayDeque<Fold>
15+
16+
private var maxX: Int
17+
private var maxY: Int
18+
19+
init {
20+
val _folds: MutableList<Fold> = mutableListOf()
21+
val list: MutableList<Pair<Int, Int>> = mutableListOf()
22+
lines.forEach { line ->
23+
when {
24+
line.startsWith("fold") -> line.replace("fold along ", "").split("=")
25+
.let { _folds.add(Fold(it[0] == "x", it[1].toInt())) }
26+
line.isBlank() -> {}
27+
else -> line.split(",").map(String::toInt).let { list.add(it[0] to it[1]) }
28+
}
29+
}
30+
folds = ArrayDeque(_folds)
31+
maxX = list.maxOf { it.first + 1 }
32+
maxY = list.maxOf { it.second + 1 }
33+
matrix = Array(maxY) { BooleanArray(maxX) }
34+
list.forEach { matrix[it.second][it.first] = true }
35+
}
36+
37+
fun fold(limit: Int = Int.MAX_VALUE) {
38+
var counter = 0
39+
do {
40+
val fold = folds.removeFirstOrNull() ?: return
41+
if (fold.x) {
42+
for (x in 0 until fold.pos) {
43+
for (y in 0 until maxY) {
44+
matrix[y][x] = matrix[y][x] || matrix[y][maxX - x - 1]
45+
}
46+
}
47+
maxX = fold.pos
48+
} else {
49+
for (x in 0 until maxX) {
50+
for (y in 0 until fold.pos) {
51+
matrix[y][x] = matrix[y][x] || matrix[maxY - y - 1][x]
52+
}
53+
}
54+
maxY = fold.pos
55+
}
56+
counter++
57+
if (counter == limit) {
58+
return
59+
}
60+
} while (true)
61+
}
62+
63+
fun print() {
64+
println()
65+
for (y in 0 until maxY) {
66+
for (x in 0 until maxX) {
67+
print(if (matrix[y][x]) "#" else ".")
68+
}
69+
println()
70+
}
71+
}
72+
73+
fun count(): Int {
74+
var result = 0
75+
for (y in 0 until maxY) {
76+
for (x in 0 until maxX) {
77+
if (matrix[y][x]) {
78+
result++
79+
}
80+
}
81+
}
82+
return result
83+
}
84+
}
85+
86+
fun File.read() = Data(readLines())
87+
88+
fun part1(data: Data): Int {
89+
// data.print()
90+
data.fold(1)
91+
// data.print()
92+
return data.count()
93+
}
94+
95+
96+
fun part2(data: Data): Int {
97+
data.fold()
98+
data.print()
99+
return 0
100+
}
101+
102+
// ---- RUN
103+
104+
val testData = File("src/day13/input_test.txt").read()
105+
val data = File("src/day13/input.txt").read()
106+
107+
verify(17, part1(testData))
108+
verify(647, part1(data))
109+
110+
verify(0, part2(testData)) // result 0
111+
verify(0, part2(data)) // result HEJHJRCJ
112+
}

0 commit comments

Comments
 (0)