Swift: Randomly generate a number from 0 to n-1 that isn't in list - COFPROG

Swift: Randomly generate a number from 0 to n-1 that isn't in list

Problem: Given an integer n and a list of integers l, write a function in swift that randomly generates a number from 0 to n-1 that isn't in list (uniform).

Solution:

 let n = 10


let excludeList = [1, 3, 5, 7]


func randomNumber(n: Int, excludeList: [Int]) -> Int {

    var result: Int

    repeat {

        result = Int.random(in: 0..<n)

    } while excludeList.contains(result)

    return result

}


let random = randomNumber(n: n, excludeList: excludeList)

print(random) // prints a random number between 0 and 9 that is not in the excludeList






Previous
Next Post »

BOOK OF THE DAY