Skip to content

Commit 5276a03

Browse files
committed
Add 2023 Day 01 Part 2 solution
1 parent 30eb520 commit 5276a03

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

adventofcode2023/Day01.kt

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,48 @@ package adventofcode2023
22

33
import java.io.File
44

5-
fun part1(file: File) {
6-
println(file.readLines().sumOf { line ->
5+
fun part1(inputs: List<String>) {
6+
println(inputs.sumOf { line ->
77
val digits = line.filter { char -> char.isDigit() }
88
digits.first().digitToInt() * 10 + digits.last().digitToInt()
99
})
1010
}
1111

12-
fun main(args: Array<String>) {
13-
val inputs = File("resources/adventofcode2023/Day01.txt")
12+
fun part2(inputs: List<String>) {
13+
val digits = setOf(
14+
Pair("one", '1'),
15+
Pair("two", '2'),
16+
Pair("three", '3'),
17+
Pair("four", '4'),
18+
Pair("five", '5'),
19+
Pair("six", '6'),
20+
Pair("seven", '7'),
21+
Pair("eight", '8'),
22+
Pair("nine", '9')
23+
)
24+
25+
fun findDigit(line: String, indices: IntProgression = line.indices): Int {
26+
for (i in indices) {
27+
for (digit in digits) {
28+
if ((line.length >= i + digit.first.length
29+
&& line.substring(i, i + digit.first.length) == digit.first)
30+
|| line[i] == digit.second
31+
) {
32+
return digit.second.digitToInt()
33+
}
34+
}
35+
}
36+
37+
return 0
38+
}
39+
40+
println(inputs.sumOf { line ->
41+
findDigit(line) * 10 + findDigit(line, line.indices.reversed())
42+
})
43+
}
44+
45+
fun main() {
46+
val inputs = File("resources/adventofcode2023/Day01.txt").readLines()
1447
part1(inputs)
48+
part2(inputs)
1549
}

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