92 lines
2.5 KiB
Text
92 lines
2.5 KiB
Text
|
#!/usr/bin/env kotlin
|
||
|
|
||
|
import java.io.File
|
||
|
import java.util.Scanner
|
||
|
import kotlin.math.abs
|
||
|
|
||
|
val expectedExampleAnswer = 11
|
||
|
val secondExpectedExampleAnswer = 31
|
||
|
|
||
|
fun useProd(): Boolean {
|
||
|
print("Run on (p)roduction values or on (e)xample values w/ a known answer? >")
|
||
|
val scanner = Scanner(System.`in`)
|
||
|
val result = scanner.next().single() == 'p'
|
||
|
if(result) {
|
||
|
print("Running in production mode\n\n")
|
||
|
return true
|
||
|
}
|
||
|
print("\nRunning in example mode, expected values are $expectedExampleAnswer and $secondExpectedExampleAnswer\n")
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
fun getChallenge(): Char {
|
||
|
val scanner = Scanner(System.`in`)
|
||
|
print("Challenge (1) or (2)? >")
|
||
|
return scanner.next().single()
|
||
|
}
|
||
|
|
||
|
fun challenge1(input: String): Int {
|
||
|
val lines = input.split("\n")
|
||
|
var invalidLines = 0
|
||
|
val leftLocations: MutableList<Int> = mutableListOf()
|
||
|
val rightLocations: MutableList<Int> = mutableListOf()
|
||
|
var answer = 0
|
||
|
|
||
|
for(line in lines) {
|
||
|
val locations = line.split(" ")
|
||
|
try {
|
||
|
leftLocations += locations[0].toInt()
|
||
|
rightLocations += locations[1].toInt()
|
||
|
}
|
||
|
catch(e: Exception) {
|
||
|
invalidLines++
|
||
|
continue
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for(i in 0..<lines.size - invalidLines) {
|
||
|
val minLeft = leftLocations.min()
|
||
|
val minRight = rightLocations.min()
|
||
|
leftLocations.remove(minLeft)
|
||
|
rightLocations.remove(minRight)
|
||
|
|
||
|
answer += abs(minLeft - minRight)
|
||
|
}
|
||
|
|
||
|
return answer
|
||
|
}
|
||
|
|
||
|
fun challenge2(input: String): Int {
|
||
|
val lines = input.split("\n")
|
||
|
var invalidLines = 0
|
||
|
val leftLocations: MutableList<Int> = mutableListOf()
|
||
|
var rightLocations: MutableList<Int> = mutableListOf()
|
||
|
var answer = 0
|
||
|
|
||
|
for(line in lines) {
|
||
|
val locations = line.split(" ")
|
||
|
try {
|
||
|
leftLocations += locations[0].toInt()
|
||
|
rightLocations += locations[1].toInt()
|
||
|
}
|
||
|
catch(e: Exception) {
|
||
|
invalidLines++
|
||
|
continue
|
||
|
}
|
||
|
}
|
||
|
|
||
|
for(location in leftLocations) {
|
||
|
val amountOfTimes = rightLocations.count { it == location }
|
||
|
answer += location * amountOfTimes
|
||
|
}
|
||
|
|
||
|
return answer
|
||
|
}
|
||
|
|
||
|
val prodCheck = useProd()
|
||
|
val file = File(if(prodCheck) "input.txt" else "example.txt")
|
||
|
val content = file.readText()
|
||
|
val challengeNumber = getChallenge()
|
||
|
|
||
|
val answer = if(challengeNumber == '1') challenge1(content) else if(challengeNumber == '2') challenge2(content) else 0
|
||
|
println("The answer is $answer!")
|