我有一个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
任何帮助?
答案 0 :(得分:1)
以随机方式选择所有数字的好方法如下。 (注意:这只是一个伪代码。)
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.