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

会有一股神秘感。 提交于 2019-12-02 17:35:37

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/27473999/how-to-grab-a-random-element-from-an-array-without-grabbing-the-same-element-mor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!