How to generate a random integer from a range [0, N] that is not in a unique integer list with Swift

1 Answer

0 votes
import Foundation

func randomExcluding(_ N: Int, excluded: Set<Int>) -> Int {
    // If all numbers are excluded, return -1
    if excluded.count > N + 1 {
        return -1
    }

    var num: Int
    repeat {
        num = Int.random(in: 0...N)
    } while excluded.contains(num)

    return num
}


let excluded: Set<Int> = [2, 5, 7]
let N = 14

let result = randomExcluding(N, excluded: excluded)
print(result)




/*
run:

1

*/

 



answered 12 hours ago by avibootz

Related questions

...