Skip to content

Instantly share code, notes, and snippets.

@abdallaadelessa
Last active June 12, 2019 07:49
Show Gist options
  • Save abdallaadelessa/a74fd0308804de3ede3c55a92a7827f3 to your computer and use it in GitHub Desktop.
Save abdallaadelessa/a74fd0308804de3ede3c55a92a7827f3 to your computer and use it in GitHub Desktop.
/*
* 1 (0,0)
* 2 (0,1)
* 3 (0,2)
* 4 (1,2)
* 5 (2,2)
* 6 (2,1)
* 7 (2,0)
* 8 (1,0)
* 9 (1,1)
*/
import java.lang.IllegalArgumentException
fun main() {
spiralMatrix(4).print()
}
fun spiralMatrix(size: Int): Array<Array<Int>> {
val defaultValue = -1
fun fill(
startY: Int,
startX: Int,
startValue: Int,
endValue: Int,
array2D: Array<Array<Int>>
): Array<Array<Int>> {
var y = startY
var x = startX
var value = startValue
if (value >= endValue) {
// Last Value
array2D[y][x] = value
return array2D
}
while (x + 1 < array2D[y].size && array2D[y][x + 1] == defaultValue) array2D[y][x++] = value++ // Go Right
while (y + 1 < array2D.size && array2D[y + 1][x] == defaultValue) array2D[y++][x] = value++ // Go Down
while (x - 1 >= 0 && array2D[y][x - 1] == defaultValue) array2D[y][x--] = value++ // Go Left
while (y - 1 >= 0 && array2D[y - 1][x] == defaultValue) array2D[y--][x] = value++ // Go Up
return fill(y, x, value, endValue, array2D)
}
return size.takeIf { size > 0 }
?.run {
fill(0, 0, 1, this * this, Array(this) { Array(this) { defaultValue } })
} ?: throw IllegalArgumentException("Size must be bigger than zero")
}
private fun Array<Array<Int>>.print() {
forEach { array ->
array.forEach { value ->
System.out.print(" ${if (value <= 9) "0$value" else value.toString()} ")
}
System.out.println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment