How to initialize a matrix with random characters in Swift

1 Answer

0 votes
import Foundation

let rows = 3
let cols = 4

func printMatrix(_ matrix: [[Character]]) {
    for row in matrix {
        for char in row {
            print(String(format: "%3c", char.asciiValue!), terminator: "")
        }
        
        print()
    }
}

func getRandomCharacter() -> Character {
    let characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    return characters.randomElement()!
}

func initializeMatrixWithRandomCharacters(rows: Int, cols: Int) -> [[Character]] {
    var matrix = [[Character]]()
    
    for _ in 0..<rows {
        var row = [Character]()
        for _ in 0..<cols {
            row.append(getRandomCharacter())
        }
        matrix.append(row)
    }
    
    return matrix
}

let matrix = initializeMatrixWithRandomCharacters(rows: rows, cols: cols)

printMatrix(matrix)



/*
run:
    
  h  x  F  Z
  8  1  U  I
  0  5  a  X
    
*/

 



answered 9 hours ago by avibootz
...