Skip to content

Instantly share code, notes, and snippets.

@funyin
Last active October 17, 2022 00:34
Show Gist options
  • Save funyin/3ad176ed1cfeb88489f06bbde404fefc to your computer and use it in GitHub Desktop.
Save funyin/3ad176ed1cfeb88489f06bbde404fefc to your computer and use it in GitHub Desktop.
Matrix Zeros
/**
* Given a 2D matrix, if an element is 0 set its entire row and column to 0. Do it in place
*
* Input:
* [[1,1,1,1],
* [1,1,1,0],
* [1,1,1,1]]
*
* Output:
* [[1,1,1,0],
* [0,0,0,0],
* [1,1,1,0]]
*/
fun main(){
val matrix = arrayOf<IntArray>(
intArrayOf(1, 1, 1, 1),
intArrayOf(1, 1, 1, 0),
intArrayOf(0, 1, 1, 1)
)
matrix.setMatrixZeros().asList().map { println(it.asList()) }
}
typealias Matrix = Array<IntArray>
fun Matrix.setMatrixZeros():Matrix{
val guiltyRows = arrayListOf<Int>()
this.forEachIndexed { index, ints ->
if (ints.contains(0))
guiltyRows.add(index)
}
var mutatedMatrix = this
for (guiltyRow in guiltyRows){
val guiltyColumn = this[guiltyRow].indexOf(0)
mutatedMatrix = this.mapIndexed {index,it->
if (index==guiltyRow) {
IntArray(it.size){
0
}
}else{
IntArray(it.size){mIndex->
if (mIndex==guiltyColumn)
0
else it[mIndex]
}
}
}.toTypedArray()
}
return mutatedMatrix
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment