Skip to content

Commit b2446e1

Browse files
committed
Add 2023 Day 03 Part 2 solution
1 parent 33e9e02 commit b2446e1

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

adventofcode2023/Day03.kt

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,61 @@ object Day03 {
6666

6767
println(sum)
6868
}
69+
70+
fun part2(inputs: List<String>) {
71+
fun getAsteriskPositions(): List<Pair<Int, Int>> {
72+
val asteriskPositions = mutableListOf<Pair<Int, Int>>()
73+
for (y in inputs.indices) {
74+
for (x in inputs[0].indices) {
75+
if (inputs[y][x] == '*') {
76+
asteriskPositions.add(Pair(x, y))
77+
}
78+
}
79+
}
80+
return asteriskPositions
81+
}
82+
83+
fun getPartNumber(x: Int, y: Int): Pair<Int, Int>? {
84+
if (inputs[y][x].isDigit()) {
85+
var number = inputs[y][x].toString()
86+
var checkLeft = x - 1
87+
var checkRight = x + 1
88+
89+
while (checkLeft >= 0 && inputs[y][checkLeft].isDigit()) {
90+
number = inputs[y][checkLeft] + number
91+
checkLeft--
92+
}
93+
while (checkRight < inputs[0].length && inputs[y][checkRight].isDigit()) {
94+
number += inputs[y][checkRight]
95+
checkRight++
96+
}
97+
98+
return Pair(checkLeft * y, number.toInt())
99+
}
100+
return null
101+
}
102+
103+
println(getAsteriskPositions().sumOf { // first: x, second: y
104+
val partNumbers = mutableListOf<Pair<Int, Int>>()
105+
106+
for (i in -1..1) {
107+
for (j in -1..1) {
108+
val number = getPartNumber(it.first + j, it.second + i)
109+
110+
if (number != null && !partNumbers.contains(number)) {
111+
partNumbers.add(number)
112+
}
113+
}
114+
}
115+
116+
if (partNumbers.size == 2) partNumbers[0].second * partNumbers[1].second else 0
117+
})
118+
}
119+
69120
}
70121

71122
fun main() {
72123
val inputs = File("resources/adventofcode2023/Day03.txt").readLines()
73124
Day03.part1(inputs)
125+
Day03.part2(inputs)
74126
}

0 commit comments

Comments
 (0)