0

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)
rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

2

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)
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

My approach will be to store the random number you get in every loop in a temp file or database, then compare the new values, if they match, generate a new random value, and then compare again against file or database, that way even if they match you assure you get a genuine value each time. Hope this "algorithm" helps you.

Jorge Carretero
  • 361
  • 2
  • 12
  • 1
    Why would you waste time and resources for storing temporary values in a file/database? Simply store them in a data structure in memory. – Dávid Pásztor Jun 04 '18 at 16:33