Search code examples
arraysswiftdictionaryarc4random

How to print all numbers from this dictionary in a random order without repeating them


The code crashes after 3 tries. How do I manage to print all 10 values without repeating them?

var windCard = [1:11,  2:12,  3:21,  4:22,  5:31,  6:32,  7:41,  8:42, 9:51, 10:52 ]

var die = 0
die = Int(arc4random())%windCard.count

print("The wind blow the mosquitoes \(windCard[Int(die)]!)")
windCard.removeValue(forKey: die)

Solution

  • The issue is that Int(arc4random())%windCard.count generates keys in the range 0 to windCard.count-1, while your keys start from 1 and after you remove the first element, the keys won't even be contiguous. So for instance if you remove a key from the middle of your Dictionary (let's say key 5), windCard will have 9 elements and hence die will be in the range 0-8, but your Dictionary will be missing a key, so your code will crash on windCard[key]! if die is 5.

    You can achieve your goal by using arc4random_uniform, which accepts an upperBound input argument and using the generated random number to subscript the keys of your windCard Dictionary, which will guaranteed to be contiguous.

    while windCard.count > 0 {
        let die = Int(arc4random_uniform(UInt32(windCard.keys.count)))
        let key = Array(windCard.keys)[die]
        print("The wind blow the mosquitoes \(windCard[key]!)")
        windCard.removeValue(forKey: key)
    }