Skip to content

Commit e838c61

Browse files
committed
Add day 8 part 2
1 parent 76828d2 commit e838c61

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

2015/src/main/kotlin/day08/Day08.kt

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,40 @@ class Day08 {
1717
return Day08Result(stateMachine.lineResults)
1818
}
1919

20-
fun part2(input: List<String>): Int {
21-
TODO("IMPLEMENT")
20+
fun part2(input: ByteArray): Int {
21+
var totalResult = 0
22+
var charCountOriginal = 0
23+
var charCountEncoded = 0
24+
25+
fun resetCount() {
26+
charCountOriginal = 0
27+
charCountEncoded = 2 // 2 for added surrounding quotes
28+
}
29+
30+
resetCount()
31+
32+
for (charBytes in input) {
33+
34+
if (charBytes == CharBytes.NEW_LINE.byte) {
35+
// Add and reset
36+
totalResult += charCountEncoded - charCountOriginal
37+
resetCount()
38+
continue
39+
}
40+
41+
charCountOriginal++
42+
43+
when(charBytes) {
44+
CharBytes.SLASH.byte -> charCountEncoded += 2
45+
CharBytes.QUOTE.byte -> charCountEncoded += 2
46+
else -> charCountEncoded++
47+
}
48+
}
49+
50+
// Add the last line
51+
totalResult += charCountEncoded - charCountOriginal
52+
53+
return totalResult
2254
}
2355

2456
class Day08Result(val lineResults: List<LineResult>) {

2015/src/test/kotlin/Day08Test.kt

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,15 +31,18 @@ internal class Day08Test {
3131

3232
@ParameterizedTest
3333
@CsvSource(
34-
"input, 0",
34+
"\"\", 4", // "" encodes to "\"\"" = 6 - 2 = 4
35+
"\"abc\", 4", // "abc" encodes to "\"abc\"" = 9 - 5 = 4
36+
"\"aaa\\\"aaa\", 6", // "aaa\"aaa" encodes to "\"aaa\\\"aaa\"" = 16 - 10 = 6
37+
"\"\\x27\", 5", // "\x27" encodes to "\"\\x27\"" = 11 - 6 = 5
3538
)
3639
fun `part2 examples`(input: String, expectedResult: Int) {
37-
assertEquals(expectedResult, Day08.part2(listOf(input)))
40+
assertEquals(expectedResult, Day08.part2(input.toByteArray()))
3841
}
3942

4043
@Test
4144
fun `part2 puzzel input`() {
42-
val input = Resource.readFileLines("day08")
43-
assertEquals(0, Day08.part2(input))
45+
val input = Resource.readFileAsBytes("day08")
46+
assertEquals(2046, Day08.part2(input))
4447
}
4548
}

0 commit comments

Comments
 (0)