generated from kotlin-hands-on/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay01.kt
61 lines (53 loc) · 1.75 KB
/
Day01.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* DAY 01 - Historian Hysteria
*
* Good warm-up!
*/
package aoc2024
import utils.println
import utils.readInput
import kotlin.math.abs
fun main() {
fun parseIDs(input: List<String>): Pair<MutableList<Int>, MutableList<Int>> {
val list1 = mutableListOf<Int>()
val list2 = mutableListOf<Int>()
// Parse data, creating two Int lists
for (line in input) {
val values = line.split("\\s+".toRegex())
list1.add(values[0].toInt())
list2.add(values[1].toInt())
}
return Pair(list1, list2)
}
fun sumDistances(list1: MutableList<Int>, list2: MutableList<Int>): Int {
// Sort for easy comparison
val sorted1 = list1.sorted()
val sorted2 = list2.sorted()
// Sum the differences between list pairs
var total = 0
for (i in sorted1.indices) {
total += abs(sorted1[i] - sorted2[i])
}
return total
}
fun similarity(list1: MutableList<Int>, list2: MutableList<Int>): Int {
var score = 0
// Similarity is sum of value in list 1 x occurrences in list 2
for (id in list1) {
val occurrences = list2.count { it == id }
score += id * occurrences
// println("$id - $occurrences - $score")
}
return score
}
// Check given test values:
val testInput = readInput(2024, "Day01_test")
val (list1test, list2test) = parseIDs(testInput)
check(sumDistances(list1test, list2test) == 11)
check(similarity(list1test, list2test) == 31)
// Work through the real data
val input = readInput(2024, "Day01")
val (list1, list2) = parseIDs(input)
sumDistances(list1, list2).println()
similarity(list1, list2).println()
}