Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fourteen
- class DockingData(input: List<String>) {
- private val instructions = input.map { Instruction(it) }
- class Instruction(input: String) {
- val mask = if (input.contains("mask"))
- input.split(" ").last() else null
- val address = if (input.contains("mem"))
- input.split("[").last().split("]").first().toLong() else null
- val value = if (input.contains("mem"))
- input.split(" ").last().toLong() else null
- }
- fun process(part2: Boolean = false): Long {
- val memory: MutableMap<Long, Long> = mutableMapOf()
- var mask = instructions.first().mask!!
- instructions.forEach { instruction ->
- if (instruction.mask != null)
- mask = instruction.mask
- else if (instruction.address != null && instruction.value != null) {
- if (part2) {
- applyBitmaskToAddress(mask, instruction.address).forEach {
- memory[it] = instruction.value
- }
- } else
- memory[instruction.address] = applyBitmaskToValue(mask, instruction.value)
- } else {
- throw RuntimeException("Instruction not parsable! $instruction")
- }
- }
- return memory.values.sum()
- }
- private fun applyBitmaskToValue(mask: String, value: Long): Long {
- val binaryValue = value.toString(2)
- var binaryResult = ""
- mask.forEachIndexed { index, bit ->
- binaryResult += (
- if (bit == 'X')
- binaryValue.getOrElse(binaryValue.length - mask.length + index) { '0' }
- else
- bit
- )
- }
- return binaryResult.toLong(2)
- }
- private fun applyBitmaskToAddress(mask: String, address: Long): List<Long> {
- val givenBinaryAddress = address.toString(2)
- var binaryAdresses = listOf("")
- mask.forEachIndexed { index, bit ->
- binaryAdresses = if (bit == 'X') {
- binaryAdresses.flatMap {
- listOf(it + 0, it + 1)
- }
- } else {
- binaryAdresses.map {
- if (bit == '0')
- it + givenBinaryAddress.getOrElse(givenBinaryAddress.length - mask.length + index) { '0' }
- else
- it + bit
- }
- }
- }
- return binaryAdresses.map { it.toLong(2) }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement