Day 2 complete, along with example

This commit is contained in:
Anthony Cicchetti 2019-12-03 17:13:10 -05:00
parent b06b658775
commit 3146306ce2
5 changed files with 74 additions and 2 deletions

2
.idea/adventOfCode2019.iml generated Normal file
View file

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

View file

@ -3,3 +3,6 @@ run day part inputFile: build
build:
./gradlew clean shadowJar
help: build
java -jar ./build/libs/adventOfCode2019-1.0-SNAPSHOT-all.jar --help

View file

@ -3,6 +3,7 @@ import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.parameters.options.required
import com.github.ajalt.clikt.parameters.types.path
import day1.Day1
import day2.Day2
import java.nio.file.Path
import kotlin.RuntimeException
@ -15,6 +16,8 @@ class CliParser: CliktCommand() {
when(val it = "${dayToRun.replace("Day", "")}.${partToRun}") {
"1.1" -> println(Day1().runPart1(inputFile))
"1.2" -> println(Day1().runPart2(inputFile))
"2.1" -> println(Day2().runPart1(inputFile))
"2.2" -> println(Day2().runPart2(inputFile))
else -> throw RuntimeException("Day or part (${it}) not implementation yet")
}
}

View file

@ -4,9 +4,72 @@ import java.nio.file.Files
import java.nio.file.Path
class Day2 {
private lateinit var initialList: List<Int>
private lateinit var currentList: MutableList<Int>
fun runPart1(inputFile: Path): Int {
loadFile(inputFile)
return solve()
}
private fun loadFile(inputFile: Path): List<String> {
return Files.readAllLines(inputFile)
fun runPart2(inputFile: Path): Int {
loadFile(inputFile)
for (noun in 0..99) {
for (verb in 0..99) {
currentList[1] = noun
currentList[2] = verb
with(solve()) {
if (this == 19690720) {
return (100 * noun) + verb
}
else reset()
}
}
}
throw RuntimeException("Can't be found")
}
private fun solve(): Int {
var index = 0
while ( true ) {
when (currentList[index]) {
1 -> {
val firstCoord = currentList[index + 1]
val secondCoord = currentList[index + 2]
val outputCoord = currentList[index + 3]
applyOperation(firstCoord, secondCoord, outputCoord) { a: Int, b: Int -> a + b }
}
2 -> {
val firstCoord = currentList[index + 1]
val secondCoord = currentList[index + 2]
val outputCoord = currentList[index + 3]
applyOperation(firstCoord, secondCoord, outputCoord) { a: Int, b: Int -> a * b }
}
99 -> {
return currentList[0]
}
else -> throw RuntimeException("Error encountered")
}
index += 4
}
}
private fun reset(): Unit {
currentList = initialList.toMutableList()
println(currentList)
}
private fun applyOperation(
firstCoord: Int,
secondCoord: Int,
outputCoord: Int,
operation: (Int, Int) -> Int
): Unit {
currentList[outputCoord] = operation(currentList[firstCoord], currentList[secondCoord])
}
private fun loadFile(inputFile: Path): Unit {
initialList = Files.newBufferedReader(inputFile).readLine().split(',').map { it.toInt() }
currentList = initialList.toMutableList()
}
}

View file

@ -0,0 +1 @@
1,9,10,3,2,3,11,0,99,30,40,50