Created
October 17, 2022 19:19
-
-
Save funyin/b5112be3cfe7885ae7b488455878375c to your computer and use it in GitHub Desktop.
Spriral Matrix
This file contains hidden or 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
/** | |
* Spiral Matrix | |
* Print all the elements in a matrix by following a spiral clockwise path in a matrix | |
* | |
* Input: | |
* [ | |
* [1 , 2, 3, 4, 5], | |
* [6 , 7, 8, 9, 10], | |
* [11 , 12, 13, 14, 15] | |
* ] | |
* | |
* Output: | |
* 1,2,3,4,5,10,15,14,13,12,11,6,7,8,9 | |
*/ | |
fun main(){ | |
val matrix = arrayOf( | |
intArrayOf(1 , 2, 3, 4, 5), | |
intArrayOf(16 , 17, 18, 19, 6), | |
intArrayOf(15 , 24, 25, 26, 7), | |
intArrayOf(14 , 23, 28, 27, 8), | |
intArrayOf(13 , 12, 11, 10, 9), | |
) | |
print(matrix.spiralParse()) | |
} | |
//Output | |
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 26, 27, 28, 23, 24, 25] | |
fun Array<IntArray>.spiralParse():List<Int>{ | |
var step = 0 | |
val mutatedArray = mutableListOf(*this) | |
val flatArray = arrayListOf<Int>() | |
if(this.isEmpty()||this.first().isEmpty()) | |
return emptyList() | |
while (mutatedArray.isNotEmpty()){ | |
when(step){ | |
//TOP | |
0 -> { | |
mutatedArray[0].forEach { | |
flatArray.add(it) | |
} | |
mutatedArray.removeFirst() | |
} | |
//Right | |
1 -> { | |
mutatedArray.forEach { | |
flatArray.add(it.last()) | |
} | |
repeat(mutatedArray.size){ | |
val element = mutatedArray[it] | |
if(element.size==1) | |
mutatedArray.removeAt(it) | |
if(element.isNotEmpty()) | |
//toIndex is exclusive | |
mutatedArray[it] = element.copyOfRange(0, toIndex = element.lastIndex) | |
} | |
} | |
//Bottom | |
2 -> { | |
mutatedArray.last().reversed().forEach { | |
flatArray.add(it) | |
} | |
mutatedArray.removeLast() | |
} | |
//Left | |
3 -> { | |
mutatedArray.reversed().forEach { | |
if(it.isNotEmpty()) | |
flatArray.add(it.first()) | |
} | |
repeat(mutatedArray.size){ | |
val element = mutatedArray[it] | |
if(element.isNotEmpty()) { | |
if(element.size==1) | |
mutatedArray.removeAt(it) | |
else | |
//toIndex is exclusive | |
mutatedArray[it] = element.copyOfRange(1, toIndex = element.lastIndex+1) | |
} | |
} | |
} | |
} | |
if (step == 3) | |
step = 0 | |
else | |
step++ | |
} | |
return flatArray | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment