gpt4 book ai didi

arrays - 如何从数组中生成单个随机项而不重复?

转载 作者:行者123 更新时间:2023-11-30 11:13:38 24 4
gpt4 key购买 nike

希望在每个操作后显示数组中的随机单词,但不让它重复。因此,如果选择“蓝色”,它将不会再次出现。

@IBAction func ShowWord(_ sender: Any) 
{
let array = ["blue","red","purple", "gold", "yellow", "orange","light blue", "green", "pink", "white", "black"]


let RandomWordGen = Int(arc4random_uniform(UInt32(array.count)))
randomWord?.text = array[RandomWordGen]

最佳答案

您可以添加一个已见索引的数组,如下所示,并每次获取随机值,直到随机获取所有数组项。您将从中得到想法,并按照自己的意愿实现自己的方式来正确地做到这一点

 //The lists of items
let items = ["blue","red","purple", "gold", "yellow", "orange","light blue", "green", "pink", "white", "black"]

//array to hold the index we have already traversed
var seenIndex = [Int]()


func chooseRandom() -> String {

if seenIndex.count == items.count { return "" } //we don't want to process if we have all items accounted for (Can handle this somewhere else)

let index = Int(arc4random_uniform(UInt32(items.count))) //get the random index

//check if this index is already seen by us
if seenIndex.contains(index) {
return chooseRandom() //repeat
}

//if not we get the element out and add that index to seen
let requiredItem = items[index]
seenIndex.append(index)
return requiredItem
}

下面列出了另一种方法。这也将为您提供随机/唯一值,但不使用递归

var items = ["blue","red","purple", "gold", "yellow", "orange","light blue", "green", "pink", "white", "black"]

//This will hold the count of items we have already displayed
var counter = 0

func ShowWord() {

//we need to end if all the values have been selected
guard counter != items.count else {
print("All items have been selected randomly")
return
}

//if some items are remaining
let index = Int(arc4random_uniform(UInt32(items.count) - UInt32(counter)) + UInt32(counter))

//set the value
randomWord?.text = items[index]

//printing for test
debugPrint(items[index])

//swap at the place, so that the array is changed and we can do next index from that index
items.swapAt(index, counter)

//increase the counter
counter += 1

}

另一种方法是利用交换功能。这里发生了以下事情

1。我们创建一个变量来了解我们从列表中选择/显示了多少项,即 var counter = 0

2。如果我们选择了所有元素,那么我们只需从方法返回

3。当你点击按钮选择一个随机值时,我们首先获取从0到数组计数范围内的随机索引

4。将随机项设置为 randomWord 即显示或执行预期的操作

5。现在我们交换元素 例如,如果您的数组是 ["red", "green", "blue"] 并且索引是 2,我们交换“red”和“blue”

6。增加计数器

7。当我们重复这个过程时,新数组将是 ["blue", "green", "red"]

8。索引将在 _counter_ 到 _Array Count_ 之间选择

关于arrays - 如何从数组中生成单个随机项而不重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51940833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com