Home > Software engineering >  check the side cells in a matrix (Kotlin)
check the side cells in a matrix (Kotlin)

Time:10-03

Hello I am doing a minesweeper program, and I need to check the side cells in a matrix to say how many mines are on the side, I am new in this language and I don't know how to check the side cells of the selected by the index. Please help, any problem or doubt I answer

the code:

fun comptaMines(mines:Int){
    var left = 0
    var bottom = n
    var right = n
    var top = 0

    for(i in 0..tablero.size){
        for(j in 0..i){
            if(j==top){

            }
        }
        println()
    }
}

CodePudding user response:

First, when you're iterating an array or list, you should not iteration from 0 all the way up to the size, because that is one too big and will reach outside it (the size plus one more for the 0). Either you can use 0 until tablero.size, or 0..tablero.size - 1 or more simply, you can use indices so you don't have to type out the range.

For the inner range that iterates the rows in the outer loop's columns, you need to iterate all the rows. It doesn't make sense for i to be part of the range you're looping. If you did that, you would only be looping through the bottom triangular half of your square (if it's a square matrix). So here's how to fix that first part:

for (i in tablero.indices) {
    for (j in tablero[i].indices) {
        val currentCell = tablero[i][j]
        // check the neighbors...
    }
}

Now we are iterating every cell coordinate in the matrix. For each cell, you want to look at all the neighbors. This is done by looking up cells that are 1 or -1 from i and j. For instance, if we are looking at cell tablero[i][j] and we want to look at the cell to the left of it, we check tablero[i-1][j]. When you do these checks, you must be careful not to check out of bounds. For instance, if i is zero, there is no cell to the left, and tablero[i-1] would give you an IndexOutOfBoundsException because there cannot be a tablero[-1]. Likewise, if i is equal to tablero.size - 1, then there is no cell to the right of it.

  • Related