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

查看:213
本文介绍了从数组中获取随机的唯一元素,直到在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

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

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