如何从数组中获取一个随机元素而又不多次获取同一元素? [英] How to grab a random element from an array without grabbing the same element more than once?
问题描述
当我使用 arc4random_uniform()
方法从数组中获取一个元素时,该数组中的同一元素通常会被多次获取。我正在尝试使数组中的每个元素仅被抓取一次。我尝试执行此操作的原因是 UITableView
中的多个单元格没有相同的文本。这是 UITableView
中单元格文本的数组:
var definitions = [[用于携带法老,用于作为仪式携带尸体,具有平坦的甲板来承载农夫的宝物,每天,它都要绕着Ra进行世界各地的旅行,
$ $$$$$
$由较小的船只拖曳,携带重物,用于官员/贵族的商务和休闲,随身携带大多数埃及人和一些物品 b
$ b
在我的 viewDidLoad()
方法中,我这样做是为了调用定义$ c的随机元素$ c>:
self.boats = [Boats(name:definitions [Int(arc4random_uniform(7))]),小船(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))]),船(名称:definitions [Int(arc4random_uniform(7))]),Boats(名称:definitions [Int(arc4random_uniform(7))])]
如何更改代码,使两个元素不会在 UITableView
中两次显示?谢谢!
保留随机索引值的列表,如果该列表中包含后续随机索引,则跳过该列表并生成另一个随机索引。
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!
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.
这篇关于如何从数组中获取一个随机元素而又不多次获取同一元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!