Search code examples
arraysuitableviewswiftrandomarc4random

How to grab a random element from an array without grabbing the same element more than once?


When I grab an element from an array using the arc4random_uniform() method, the same element the array is often grabbed more than once. I am trying to make it so each element in the array is grabbed only once. The reason I'm trying to do this is so more than one cells in a UITableView don't have the same text. Here's the array for the text of the cells in the UITableView:

var definitions = ["Used to carry the pharoah","Used to carry bodies as a ceremony","Had a flat deck to carry a farmer's treasure","Daily, it made a trip around the world to carry Ra","Towed by smaller boats, carrying heavy objects","Used for business and pleasure by officials/nobles","Carried most Egyptians and some goods"]

In my viewDidLoad() method, I have done this to call random elements of definitions:

self.boats = [Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))]),Boats(name: definitions[Int(arc4random_uniform(7))])]

How can I alter my code so two elements aren't displayed twice in my UITableView? Thank you!


Solution

  • Keep a list of the random index values and if a subsequent random index is in that list, then skip it and generate another random index.