Advertisement
Guest User

BinaryDiagnostic

a guest
Dec 4th, 2021
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.98 KB | None | 0 0
  1. private fun main() {
  2.     fun part1(input: List<Int>, bitsCount: Int): Int {
  3.         var gammaRate = 0
  4.         var epsilonRate = 0
  5.         repeat(bitsCount) { index ->
  6.             val numberOfOnes = input.map { getBitAt(it, index) }.count { it == 1 }
  7.             val half = input.size.toFloat() / 2
  8.             if (numberOfOnes > half) {
  9.                 gammaRate = gammaRate or (1 shl index)
  10.             } else if (numberOfOnes < half) {
  11.                 epsilonRate = epsilonRate or (1 shl index)
  12.             } else error("There's same number of zeros and ones.")
  13.         }
  14.         return gammaRate * epsilonRate
  15.     }
  16.  
  17.     fun part2(input: List<Int>, bitsCount: Int): Int {
  18.         val oxygenGeneratorRatingList = input.toMutableList()
  19.         var oxygenGeneratorIndex = bitsCount - 1
  20.         while (oxygenGeneratorRatingList.size != 1) {
  21.             val half = oxygenGeneratorRatingList.size.toFloat() / 2
  22.             val mostCommonValueAtPosition = if (oxygenGeneratorRatingList.map { getBitAt(it, oxygenGeneratorIndex) }
  23.                     .count { it == 1 } >= half) 1 else 0
  24.             oxygenGeneratorRatingList.removeAll { getBitAt(it, oxygenGeneratorIndex) != mostCommonValueAtPosition }
  25.             oxygenGeneratorIndex--
  26.         }
  27.  
  28.         val coTwoScrubberRatingList = input.toMutableList()
  29.         var coTwoScrubberRatingIndex = bitsCount - 1
  30.         while (coTwoScrubberRatingList.size != 1) {
  31.             val half = coTwoScrubberRatingList.size.toFloat() / 2
  32.             val leastCommonValueAtPosition = if (coTwoScrubberRatingList.map { getBitAt(it, coTwoScrubberRatingIndex) }
  33.                     .count { it == 1 } < half) 1 else 0
  34.             coTwoScrubberRatingList.removeAll { getBitAt(it, coTwoScrubberRatingIndex) != leastCommonValueAtPosition }
  35.             coTwoScrubberRatingIndex--
  36.         }
  37.         return oxygenGeneratorRatingList.first() * coTwoScrubberRatingList.first()
  38.     }
  39. }
  40.  
  41. private fun getBitAt(number: Int, index: Int): Int = number shr index and 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement