Guest User

Advent Of Code 2021 Day 7 solutions

a guest
Dec 21st, 2021
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.15 KB | None | 0 0
  1. import kotlin.math.abs
  2. import kotlin.math.ceil
  3. import kotlin.math.floor
  4.  
  5. // assuming the input has already been parsed
  6.  
  7. // the optimal position is the one at the index which corresponds to the median of the sorted list
  8. fun part1(positions: List<Int>): Int {
  9.     val sorted = positions.sorted()
  10.     val medianPosition = positions.size / 2
  11.  
  12.     return positions.sumOf { abs(sorted[medianPosition] - it) }
  13. }
  14.  
  15. fun Double.gauss() = this * (this + 1) / 2
  16.  
  17. fun List<Int>.solve(roundedMean: Double) = this.sumOf { abs(roundedMean - it).gauss() }
  18.  
  19. // the mean approximates the optimal position but there's a variation of +/- 0.5, so the calculation
  20. // must be performed once with the minimum between the floor and the ceiling of the mean, and once
  21. // with the maximum. the solution is the lower of the two results
  22. fun part2(positions: List<Int>): Int {
  23.     val mean = positions.sum().toDouble() / positions.size
  24.     val meanFloor = floor(mean)
  25.     val meanCeil = ceil(mean)
  26.     val roundedLow = positions.solve(minOf(meanFloor, meanCeil))
  27.     val roundedHigh = positions.solve(maxOf(meanFloor, meanCeil))
  28.  
  29.     return minOf(roundedLow, roundedHigh).toInt()
  30. }
Advertisement
Add Comment
Please, Sign In to add comment