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

1 Answer

0 votes
import Foundation

let ROWS = 5
let COLS = 4

func fillMatrixWithRandom0and1(matrix: inout [[Int]], rows: Int, cols: Int) {
    for i in 0..<rows {
        for j in 0..<cols {
            matrix[i][j] = Int.random(in: 0...1) // Generates either 0 or 1
        }
    }
}

func printMatrix(matrix: [[Int]], rows: Int, cols: Int) {
    for i in 0..<rows {
        for j in 0..<cols {
            print(matrix[i][j], terminator: " ")
        }
        print()
    }
}

var matrix = Array(repeating: Array(repeating: 0, count: COLS), count: ROWS)

fillMatrixWithRandom0and1(matrix: &matrix, rows: ROWS, cols: COLS)

printMatrix(matrix: matrix, rows: ROWS, cols: COLS)



/*
run:

0 0 0 1 
1 0 1 1 
0 1 1 0 
1 1 1 0 
1 1 0 1 

*/

 



answered Jan 26, 2025 by avibootz

Related questions

1 answer 97 views
1 answer 91 views
1 answer 86 views
1 answer 89 views
1 answer 76 views
...