如何使一个数字不重复超过2次?

时间:2016-12-17 14:20:53

标签: ios swift xcode random repeat

大家好!让我们说我们有

let random = arc4random_uniform(6)

如何让它不再重复两次相同的数字?我尝试这样做:

let previousNumber = Int()
let lastNumber = Int ()

let random = Int(arc4random_uniform(6))

if random == previousNumber {
  lastNumber = previousNumber
} else {
previousNumber = random 
}

if random == lastNumber {
random = Int(arc4random_uniform(6))
}

但它没有用。我是swift的新手,我没有在新的swift 3代码上找到关于此主题的话题。谢谢 !

1 个答案:

答案 0 :(得分:1)

首先,让我们构建一个类来保存所选值的近期历史记录

class History {

    private let size: Int
    private var values = [Int]()

    init(size:Int) {
        self.size = size
    }

    func add(value: Int) {
        values.insert(value, at: 0)
        if values.count > size {
            values.removeLast()
        }
    }

    var repeatedValueOnFullHistory: Int? {
        guard Set(values).count <= 1 else { return nil }
        return values.first
    }

}

接下来让我们构建一个Randomizer

class Randomizer {
    private var allValues = [Int]()
    private var history: History

    init?(maxValue: Int) {
        guard maxValue > 0 else { return nil }
        self.allValues = Array(0...maxValue)
        self.history = History(size: maxValue + 1)
    }

    var next: Int {
        let excludedValue = history.repeatedValueOnFullHistory
        let allowedValues = allValues.filter { excludedValue != $0 }

        let randomIndex = Int(arc4random_uniform(UInt32(allowedValues.count)))

        let nextValue = allowedValues[randomIndex]
        history.add(value: nextValue)
        return nextValue
    }
}

最后让我们测试一下

if let r = Randomizer(maxValue: 6) {
    r.next // 6
    r.next // 2
    r.next // 1
    r.next // 4
    r.next // 6
    r.next // 4
    r.next // 1
}