Created
January 20, 2018 10:49
-
-
Save whaley/5d7c7f9132b68b7883be4497ef9d49a3 to your computer and use it in GitHub Desktop.
This file contains 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
fun manhattan(x: Int): Int { | |
val y = nextOddPerfectSquareInclusive(x) | |
val max = sqrt(y.toDouble()).roundToInt() - 1 | |
val min = max / 2 | |
val f = if (max == 0) 0 else max - ((y - x) % max) //for 33, f is 2, needs to be 4 | |
return if (f < min) max - f else f | |
} | |
fun nextOddPerfectSquareInclusive(x: Int): Int { | |
for (i in 1..x step 2) { | |
val iSquared = Math.pow(i.toDouble(), 2.toDouble()).roundToInt() | |
val nextSquared = Math.pow((i + 2).toDouble(), 2.toDouble()).roundToInt() | |
if (x == iSquared) return x | |
else if (x > iSquared && x < nextSquared) return nextSquared | |
else continue | |
} | |
throw IllegalStateException() | |
} |
This file contains 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
object Day03Spec : Spek({ | |
given("Day Three : Part One") { | |
val testData = mapOf(1 to 0, 9 to 2, 10 to 3, 12 to 3, 23 to 2, 27 to 4, 33 to 4, 35 to 4, 40 to 3, 47 to 4, 48 to 5,1024 to 31) | |
on("manhattan") { | |
for ((input, expected) in testData) { | |
it("should return $expected when given input of $input") { | |
assertEquals(expected, manhattan(input)) | |
} | |
} | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment