从 Array 中获取一个随机的唯一元素,直到在 Swift 中选择了所有元素 [英] Get a random unique element from an Array until all elements have been picked in Swift

查看:21
本文介绍了从 Array 中获取一个随机的唯一元素,直到在 Swift 中选择了所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组:

var notebookCovers = ["cover1", "cover2", "cover3", "cover4", "cover4", "cover6", "cover7", "cover8", "cover9", "cover10"]

和一个 UIButton ,当它被按下时它会生成一个新的 UIImage 与数组的元素之一.

and a UIButton that when it's pressed it generates a new UIImage with one of the elements of the array.

我需要做的是每次点击按钮时从数组中生成随机但唯一的元素(不重复元素),直到它们都被选中,然后再次重新启动数组.

What I need to do is every time the button is tapped to generate random but unique element from the array (without repeating the elements) until they've all been selected and then restart the array again.

到目前为止,我得到了一个随机元素,但它重复了,我不知道怎么做,所以每次都会得到一个独特的图像

So far, I have it getting a random element but it's repeated and I cannot figure out how to it so it gets a unique image every time

func createNewNotebook() {
    let newNotebook = Notebook()
    let randomInt = randomNumber()
    newNotebook.coverImageString = notebookCovers[randomInt]
    notebooks.insert(newNotebook, at: 0)
    collectionView.reloadData()
}

func randomNumber() -> Int {
    var previousNumber = arc4random_uniform(UInt32(notebookCovers.count))   
    var randomNumber = arc4random_uniform(UInt32(notebookCovers.count - 1)) 
    notebookCovers.shuffle()
    if randomNumber == previousNumber {
        randomNumber = UInt32(notebookCovers.count - 1)
    }
    previousNumber = randomNumber
    return Int(randomNumber)
}

推荐答案

复制数组.随机复制.现在只需继续删除第一个元素,直到副本为空.当它为空时,重新开始.

Copy the array. Shuffle the copy. Now just keep removing the first element until the copy is empty. When it is empty, start over.

示例:

let arr = [1,2,3,4,5]
var copy = [Int]()
for _ in 1...30 { // just to demonstrate what happens
    if copy.isEmpty { copy = arr; copy.shuffle() }
    let element = copy.removeFirst() ; print(element, terminator:" ")
}
// 4 2 3 5 1 1 5 3 2 4 4 1 2 3 5 1 4 5 2 3 3 5 4 2 1 3 2 4 5 1

这篇关于从 Array 中获取一个随机的唯一元素,直到在 Swift 中选择了所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆