How to fill an array with 1 and 0 in random locations with Swift

1 Answer

0 votes
import Foundation

func fillArrayWithRandom1and0(_ array: inout [Int]) {
    for i in 0..<array.count {
        array[i] = Int.random(in: 0...1) // Generates either 0 or 1
    }
}

let size = 10
var array = Array(repeating: 0, count: size)

fillArrayWithRandom1and0(&array)

print(array.map(String.init).joined(separator: " "))




/*
run:

0 1 0 1 1 0 0 0 1 0

*/

 



answered Jan 26, 2025 by avibootz

Related questions

...