Created
December 27, 2017 16:52
-
-
Save vishnumad/128a3cb430ababf4daae7644d1eb4e18 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.File | |
| var largestSeenValue = 0 | |
| fun main(args: Array<String>) { | |
| val instructions = File("input.txt").readLines() | |
| println("Part 1: largest value = ${getLargestValue(instructions)}") | |
| println("Part 2: largest seen value = $largestSeenValue") | |
| } | |
| fun getLargestValue(instructions: List<String>) : Int { | |
| val registers = mutableListOf<Register>() | |
| instructions.forEach { | |
| val command = it.substringBefore(" if").split(" ") | |
| val condition = it.substringAfter("if ").split(" ") | |
| if (hasMetCondition(condition, registers)) { | |
| executeCommand(command, registers) | |
| } | |
| } | |
| registers.sortByDescending { it.value } | |
| return registers[0].value | |
| } | |
| private fun hasMetCondition(condition: List<String>, registers: MutableList<Register>) : Boolean { | |
| registers.addRegister(Register(condition[0])) | |
| val register = registers.getRegister(condition[0]) | |
| return when(condition[1]) { | |
| "==" -> register.value == condition[2].toInt() | |
| "!=" -> register.value != condition[2].toInt() | |
| ">=" -> register.value >= condition[2].toInt() | |
| "<=" -> register.value <= condition[2].toInt() | |
| ">" -> register.value > condition[2].toInt() | |
| "<" -> register.value < condition[2].toInt() | |
| else -> false | |
| } | |
| } | |
| private fun executeCommand(command: List<String>, registers: MutableList<Register>) { | |
| registers.addRegister(Register(command[0])) | |
| val register = registers.getRegister(command[0]) | |
| when(command[1]) { | |
| "inc" -> register.inc(command[2].toInt()) | |
| "dec" -> register.dec(command[2].toInt()) | |
| } | |
| if (register.value > largestSeenValue) largestSeenValue = register.value | |
| } | |
| private fun List<Register>.getRegister(name: String) = this.first { it == Register(name) } | |
| private fun MutableList<Register>.addRegister(register: Register) { | |
| if (register !in this) add(register) | |
| } | |
| private data class Register(val name: String, var value: Int) { | |
| constructor(name: String) : this(name, 0) | |
| fun dec(x: Int) { | |
| value -= x | |
| } | |
| fun inc(x: Int) { | |
| value += x | |
| } | |
| override fun equals(other: Any?): Boolean { | |
| if (other is Register) { | |
| return this.name == other.name | |
| } | |
| return false | |
| } | |
| override fun hashCode(): Int { | |
| return name.hashCode() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment