0

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!

TheCentral
  • 35
  • 1
  • 6
  • Do you want to randomly sort the array? – Leo Dabus Dec 14 '14 at 21:01
  • What you are looking for is called "random shuffle" or "random permutation". The [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle) is one possible implementation. – Martin R Dec 14 '14 at 21:05

1 Answers1

0

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.

mbmast
  • 960
  • 11
  • 25
  • 1
    This is not the best way to do this, if you want to get all of the elements it gets very inefficient towards the end. – pjs Dec 15 '14 at 01:38
  • Agreed. An alternative would be to use a linked list with n elements. Generate a random index i, 1 <= i <= n (assuming a 1 offset), grab the value, remove the item from the list (so the list is now n-1 elements) and do it again, this time generating a random index i between 1 and n-1. Or some variation on that theme. – mbmast Dec 16 '14 at 21:28
  • Better alternatives would be to shuffle the set of values and iterate through the shuffled set (to get the entire set), or to use [Floyd's unique subset algorithm](http://stackoverflow.com/questions/27157311/randomly-skip-x-percentage-of-words-from-java-iterator/27160949#27160949) if you want a subset. – pjs Dec 16 '14 at 21:41