Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private fun main() {
- fun part1(input: List<Int>, bitsCount: Int): Int {
- var gammaRate = 0
- var epsilonRate = 0
- repeat(bitsCount) { index ->
- val numberOfOnes = input.map { getBitAt(it, index) }.count { it == 1 }
- val half = input.size.toFloat() / 2
- if (numberOfOnes > half) {
- gammaRate = gammaRate or (1 shl index)
- } else if (numberOfOnes < half) {
- epsilonRate = epsilonRate or (1 shl index)
- } else error("There's same number of zeros and ones.")
- }
- return gammaRate * epsilonRate
- }
- fun part2(input: List<Int>, bitsCount: Int): Int {
- val oxygenGeneratorRatingList = input.toMutableList()
- var oxygenGeneratorIndex = bitsCount - 1
- while (oxygenGeneratorRatingList.size != 1) {
- val half = oxygenGeneratorRatingList.size.toFloat() / 2
- val mostCommonValueAtPosition = if (oxygenGeneratorRatingList.map { getBitAt(it, oxygenGeneratorIndex) }
- .count { it == 1 } >= half) 1 else 0
- oxygenGeneratorRatingList.removeAll { getBitAt(it, oxygenGeneratorIndex) != mostCommonValueAtPosition }
- oxygenGeneratorIndex--
- }
- val coTwoScrubberRatingList = input.toMutableList()
- var coTwoScrubberRatingIndex = bitsCount - 1
- while (coTwoScrubberRatingList.size != 1) {
- val half = coTwoScrubberRatingList.size.toFloat() / 2
- val leastCommonValueAtPosition = if (coTwoScrubberRatingList.map { getBitAt(it, coTwoScrubberRatingIndex) }
- .count { it == 1 } < half) 1 else 0
- coTwoScrubberRatingList.removeAll { getBitAt(it, coTwoScrubberRatingIndex) != leastCommonValueAtPosition }
- coTwoScrubberRatingIndex--
- }
- return oxygenGeneratorRatingList.first() * coTwoScrubberRatingList.first()
- }
- }
- private fun getBitAt(number: Int, index: Int): Int = number shr index and 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement