簡體   English   中英

快速生成不在數組中的隨機數

[英]Generate random number not in array in swift

我想生成一個不在數組中的隨機數。 如果是,那么它將繼續生成,直到生成一個不是的數字。 然后它將該數字附加到數組中。

第一次之后,它不起作用。 由於數組為空,因此第一次總是有效。 我認為我的while循環有問題。

這是我的代碼:

var selectQuestion: UInt32 = 0
var questionsArray:[UInt32] = []
var questionNotAsked = false

if (questionsArray.isEmpty == true) {
    questionNotAsked = true
    selectQuestion = arc4random_uniform(10)
}

while(!questionNotAsked) {
    selectQuestion = arc4random_uniform(10) //0-9
    for questions in self.questionsArray {
        if selectQuestion == questions {
            self.questionNotAsked = false
            return
        } else {
            self.questionNotAsked = true
        }
    }
}

如果您只查找 0 到 9 之間的數字,請使用這些值填充數組並對其進行洗牌 然后遍歷您需要的任何數量。 如果你到了最后,重新洗牌並重復。

這就像一個任務。 做它並研究它。 這是一個非常有用和有趣的體驗。

我只是按照你想要達到的目標。 有更優雅的方法來實現這一點。

    var questionsArray:[UInt32] = []

    func nextRandom(){

    var selectQuestion: UInt32 = 0
    var questionNotAsked = false

    while(!questionNotAsked) {
        selectQuestion = arc4random_uniform(10) //0-9
        for questions in questionsArray {
            if selectQuestion == questions {
                questionNotAsked = true
                break;
            }
        }
        questionNotAsked = !questionNotAsked
        if questionNotAsked {
             questionsArray.append(selectQuestion)}
        }
    }

      nextRandom()
      nextRandom()
      nextRandom()
      nextRandom()
      nextRandom()
    nextRandom()
    nextRandom()
    nextRandom()
    nextRandom()
    nextRandom()

    print(questionsArray)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM