How to fill a matrix with 1 and 0 in random locations with Kotlin

1 Answer

0 votes
import kotlin.random.Random

const val ROWS = 5
const val COLS = 4

fun main() {
    val matrix = Array(ROWS) { IntArray(COLS) }

    fillMatrixWithRandom0and1(matrix, ROWS, COLS)
    printMatrix(matrix, ROWS, COLS)
}

fun fillMatrixWithRandom0and1(matrix: Array<IntArray>, rows: Int, cols: Int) {
    val rand = Random
    
    for (i in 0 until rows) {
        for (j in 0 until cols) {
            matrix[i][j] = rand.nextInt(2) // Generates either 0 or 1
        }
    }
}

fun printMatrix(matrix: Array<IntArray>, rows: Int, cols: Int) {
    for (i in 0 until rows) {
        for (j in 0 until cols) {
            print("${matrix[i][j]} ")
        }
        println()
    }
}
  
  
   
/*
run:
 
1 1 0 1 
1 0 1 0 
1 0 1 1 
1 1 1 0 
0 0 0 0 
 
*/

 



answered Jan 26, 2025 by avibootz

Related questions

1 answer 94 views
1 answer 99 views
1 answer 86 views
1 answer 89 views
1 answer 76 views
...