我有一个Int数组,我想从数组中随机选取一个Int,用特定的条件填充2D网格。我尝试了下面的代码,它运行了一段时间,但在某些情况下,它运行的是无限while循环。

    for row in 0..<NumRows {
        for column in 0..<NumColumns {

                var gemType:GemType

                if gemArray.count == 1 {

                   gemType = GemType(rawValue: gemArray[0])!

                } else {

                    do {

                        index = Int(arc4random_uniform(UInt32(gemArray.count)))

                        gemType = GemType(rawValue: gemArray[index])!

                    } while (column >= 1 &&
                        gems[column - 1, row]?.gemType == gemType)
                        || (row >= 1 &&
                            gems[column, row - 1]?.gemType == gemType)

                    if gemArray.count > 0 {

                        gemArray.removeAtIndex(index)
                    }
                }

                let gem = Gem(column: column, row: row, gemType: gemType)
                gems[column, row] = gem

                // 4
                set.insert(gem)
            }
        }
    }
    return set

有什么帮助吗?

最佳答案

一个随机选择所有数字的好方法如下。(注意:这只是一个伪代码。)

Suppose array is of size [1...n]
1. k=n
2. Choose a random number between 1 to k. Let it be x.
3. Swap a[k] with a[x]. Your chosen random number is a[x].
4. k=k-1.
5. Loop until k=1.

09-25 21:07