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

时间:2018-08-21 02:38:02

标签: arrays swift arraylist random replace

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

@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]

1 个答案:

答案 0 :(得分:0)

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

 //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. We create a variable to know how many items we have selected/displayed from the list i.e var counter = 0

2. If we have selected all the elements then we simply return from the method

3. When you click the button to select a random value, we first get the random index in the range from 0 to array count

4. Set the random item to randomWord i.e display or do what is intended

5. now we swap the element       e.g if your array was ["red", "green", "blue"] and the index was 2 we swap "red" and "blue"

6. Increase the counter

7. when we repeat the process the new array will be ["blue", "green", "red"]

8. The index will be selected between _counter_ to _Array Count_