@@ -3,7 +3,7 @@ private const val DAY = 10
33fun main () {
44 fun part1 (input : List <String >): Int {
55 var syntaxErrorScore = 0
6- input.mapIndexed { lineNumber, line ->
6+ input.map { line ->
77 val expectedCloseSigns = mutableListOf<Char >()
88 line.forEach { actualChar ->
99 when (actualChar) {
@@ -12,8 +12,7 @@ fun main() {
1212 ' {' -> expectedCloseSigns.add(' }' )
1313 ' <' -> expectedCloseSigns.add(' >' )
1414 ' ]' , ' )' , ' }' , ' >' -> {
15- val expected = expectedCloseSigns.removeLast()
16- if (expected != actualChar) {
15+ if (expectedCloseSigns.removeLast() != actualChar) {
1716 syntaxErrorScore + = getSyntaxErrorPoints(actualChar)
1817 return @forEach
1918 }
@@ -25,24 +24,75 @@ fun main() {
2524 return syntaxErrorScore
2625 }
2726
28- fun part2 (input : List <String >): Int {
29- return - 1
27+ fun part2 (input : List <String >): Long {
28+ val totalScoresLines = mutableListOf<Long >()
29+ val incompleteLines = input.removeCorruptedLines()
30+ incompleteLines.map { line ->
31+ val expectedCloseSigns = mutableListOf<Char >()
32+ line.forEach { actualChar ->
33+ when (actualChar) {
34+ ' [' -> expectedCloseSigns.add(' ]' )
35+ ' (' -> expectedCloseSigns.add(' )' )
36+ ' {' -> expectedCloseSigns.add(' }' )
37+ ' <' -> expectedCloseSigns.add(' >' )
38+ ' ]' , ' )' , ' }' , ' >' -> expectedCloseSigns.removeLast()
39+ }
40+ }
41+ var totalScore = 0L
42+ expectedCloseSigns.reversed().forEach { char ->
43+ totalScore * = 5
44+ totalScore + = getAutocompletePoints(char)
45+ }
46+ totalScoresLines.add(totalScore)
47+ }
48+
49+ return totalScoresLines.sorted()[totalScoresLines.size / 2 ]
3050 }
3151
3252 // test if implementation meets criteria from the description, like:
3353 val testInput = readInput(day = DAY , useTestInput = true )
3454 check(part1(testInput) == 26397 )
35- // check(part2(testInput) == 1134 )
55+ check(part2(testInput) == 288957L )
3656
3757 val input = readInput(day = DAY )
3858 println (part1(input))
3959 println (part2(input))
4060}
4161
62+ private fun List<String>.removeCorruptedLines (): List <String > {
63+ return filter { line ->
64+ val expectedCloseSigns = mutableListOf<Char >()
65+ var isLegal = true
66+ line.forEach { actualChar ->
67+ when (actualChar) {
68+ ' [' -> expectedCloseSigns.add(' ]' )
69+ ' (' -> expectedCloseSigns.add(' )' )
70+ ' {' -> expectedCloseSigns.add(' }' )
71+ ' <' -> expectedCloseSigns.add(' >' )
72+ ' ]' , ' )' , ' }' , ' >' -> {
73+ if (expectedCloseSigns.removeLast() != actualChar) {
74+ isLegal = false
75+ return @forEach
76+ }
77+ }
78+ }
79+ }
80+ isLegal
81+ }
82+ }
83+
4284private fun getSyntaxErrorPoints (char : Char ) = when (char) {
4385 ' )' -> 3
4486 ' ]' -> 57
4587 ' }' -> 1197
4688 ' >' -> 25137
4789 else -> throw Error (" unexpected char" )
90+ }
91+
92+ private fun getAutocompletePoints (char : Char ) = when (char) {
93+ ' )' -> 1
94+ ' ]' -> 2
95+ ' }' -> 3
96+ ' >' -> 4
97+ else -> throw Error (" unexpected char" )
4898}
0 commit comments