本文介绍了抢了2个不一样的randomElements?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在这样的字符串中获取2个不同的随机值

I am trying to grab 2 random values that are not the same in a string like this

    var players = ["Jack, John, Michael, Peter"]
    var playersArray = ["\(players.randomElement) and \(players.randomElement) has to battle")

我该怎么做,因此它具有2个不同的值?

How am i to do this, so it grabs 2 different values?

推荐答案

前一段时间,我创建了一个类RandomObjects,该类维护对象数组,可用于提供来自数组中的随机,非重复对象一次.它的工作方式是维护一个索引数组,然后从索引数组中删除一个索引,直到耗尽为止.

A while back I created a class RandomObjects that maintained an array of objects and could be used to serve up random, non-repeating objects from the array one at a time. It works by maintaining an array of indexes and removing an index from the indexes array until it's depleted.

甚至提供了在返回所有值之后重新填充"索引的规定,以及避免在重新填充索引数组之后返回相同值的逻辑.

It even has a provision to "refill" the indexes after all the values have been returned, and logic to avoid the same value from being returned after the indexes array is refilled.

它是用Swift 2编写的,但我刚刚将其更新为Swift 4并将其发布到了GitHub:

It was written in Swift 2, but I just updated it to Swift 4 and posted it to GitHub:

https://github.com/DuncanMC/RandomObjects.git

该类的定义如下:

class RandomObjects<T> {
    var objectsArray: [T]
    var indexes: [Int]!
    var oldIndex: Int?

该类代码的关键是这个功能:

The key bit of code from that class is this function:

public func randomObject(refillWhenEmpty: Bool = true) -> T? {
    var randomIndex: Int
    var objectIndex: Int

    if refillWhenEmpty {
        fillIndexesArray()
    } else if indexes.isEmpty {
        return nil
    }
    repeat {
        randomIndex = Int(arc4random_uniform(UInt32(indexes.count)))
        objectIndex = indexes[randomIndex]
    } while objectIndex == oldIndex

    indexes.remove(at: randomIndex)

    oldIndex = objectIndex
    return objectsArray[objectIndex];
}

仅当您遍历数组中的每个对象并重新填充了索引数组时,才需要检查objectIndex == oldIndex.这样可以确保您不会重复上一个条目.

The check for objectIndex == oldIndex is only needed when you have gone through every object in the array and have just repopulated the indexes array. It makes sure you don't repeat the last entry.

这篇关于抢了2个不一样的randomElements?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:30
查看更多