Skip to content

Instantly share code, notes, and snippets.

@whaley
Created January 10, 2018 12:36
Show Gist options
  • Save whaley/7dc2b77658c393583c80925e7d395089 to your computer and use it in GitHub Desktop.
Save whaley/7dc2b77658c393583c80925e7d395089 to your computer and use it in GitHub Desktop.
fun checksum(spreadsheet: String, lineSummer: (List<Int>) -> Int = ::minAndMax): Int {
val lines = spreadsheet.split("\n")
val rows: List<List<Int>> = lines.map { line -> line.split(Regex("""\s""")).map { num -> Integer.valueOf(num) } }
return rows.fold(0, { sum: Int, list -> sum + lineSummer(list)})
}
fun minAndMax(list: List<Int>): Int {
return abs((list.max() ?: 0) - (list.min() ?: 0))
}
fun evenlyDivides(list: List<Int>): Int {
val pair : Pair<Int,Int>? = allPairs(list).find { it -> it.first % it.second == 0 || it.second % it.first == 0 }
return when {
pair == null -> 0
pair.first > pair.second -> pair.first / pair.second
else -> pair.second / pair.first
}
}
fun <T> allPairs(list: List<T>): List<Pair<T, T>> {
val pairs = arrayListOf<Pair<T, T>>()
for ((index, left) in list.withIndex()) {
if (index != list.size - 1) {
list.subList(index + 1, list.size).mapTo(pairs) { left to it }
}
}
return pairs
}
object Day02Spec : Spek({
given("Day Two : Part One") {
val spreadsheet = """5 1 9 5
.7 5 3
.2 4 6 8""".trimMargin(".")
on("checksum") {
assertEquals(18,checksum(spreadsheet))
}
}
given("Day Two : Part Two") {
val spreadsheet = """5 9 2 8
.9 4 7 3
.3 8 6 5""".trimMargin(".")
on("checksum with passed in function") {
assertEquals(9,checksum(spreadsheet, ::evenlyDivides))
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment