Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import kotlin.math.abs
- import kotlin.math.ceil
- import kotlin.math.floor
- // assuming the input has already been parsed
- // the optimal position is the one at the index which corresponds to the median of the sorted list
- fun part1(positions: List<Int>): Int {
- val sorted = positions.sorted()
- val medianPosition = positions.size / 2
- return positions.sumOf { abs(sorted[medianPosition] - it) }
- }
- fun Double.gauss() = this * (this + 1) / 2
- fun List<Int>.solve(roundedMean: Double) = this.sumOf { abs(roundedMean - it).gauss() }
- // the mean approximates the optimal position but there's a variation of +/- 0.5, so the calculation
- // must be performed once with the minimum between the floor and the ceiling of the mean, and once
- // with the maximum. the solution is the lower of the two results
- fun part2(positions: List<Int>): Int {
- val mean = positions.sum().toDouble() / positions.size
- val meanFloor = floor(mean)
- val meanCeil = ceil(mean)
- val roundedLow = positions.solve(minOf(meanFloor, meanCeil))
- val roundedHigh = positions.solve(maxOf(meanFloor, meanCeil))
- return minOf(roundedLow, roundedHigh).toInt()
- }
Advertisement
Add Comment
Please, Sign In to add comment