generated from henningBunk/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day07.kt
77 lines (59 loc) · 1.87 KB
/
Day07.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package day07
import common.InputRepo
import common.readSessionCookie
import common.solve
import java.util.Collections.max
import java.util.Collections.min
import kotlin.math.abs
fun main(args: Array<String>) {
val day = 7
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay07Part1, ::solveDay07Part2)
}
fun solveDay07Part1(input: List<String>): Int {
return median(input)
// return bruteforce(input)
}
private fun bruteforce(input: List<String>): Int {
val positions = parsePositions(input)
var min: Int = Int.MAX_VALUE
for (position in positions) {
val sumOf = positions.sumOf { abs(it - position) }
if (sumOf < min) {
min = sumOf;
}
}
return min
}
fun median(input: List<String>): Int {
val positions = parsePositions(input)
var median = positions.sorted()[positions.size / 2]
return positions.sumOf { abs(it - median) }
}
fun solveDay07Part2(input: List<String>): Int {
return bruteforce2(input);
}
private fun bruteforce2(input: List<String>): Int {
val positions = parsePositions(input).sorted()
var min: Int = Int.MAX_VALUE
print(positions)
for (goal in min(positions)..max(positions)) {
val sumOf = positions.sumOf { pos ->
val sum = generateSequence(0) { if (it < abs(pos - goal)) it + 1 else null }.sum()
println("$sum fuel for goal $goal from $pos")
sum
}
println("===============================")
println("Total: $sumOf")
if (sumOf < min) {
min = sumOf;
println("NEW MIN: $sumOf")
} else {
// no new min in the sorted list means, we're done
break
}
}
return min
}
private fun parsePositions(input: List<String>) =
input.map { line -> line.split(",").map(String::toInt) }.flatten()