我想说如果某个2d数组包含“点”格式[Int,Int],那么重新生成随机数,不计算迭代次数。
for _ in 0..<33{
let j = Int(arc4random_uniform(10))
let k = Int(arc4random_uniform(10))
while live.contains(//The point j,k){
live.append(Array(arrayLiteral: j,k))
cells[j][k] = true
}
}
答案 0 :(得分:2)
根据我的理解你的问题,你想要生成一个2D点数组,不包括重复,你可以使用CGPoint
或定义你自己的Point
struct Point: Equatable {
let x: Int
let y: Int
}
func == (lhs: Point, rhs: Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
var live: [Point] = []
for _ in 0..<10{
var candidate = Point(x: Int(arc4random_uniform(10)), y: Int(arc4random_uniform(10)))
while live.contains(candidate) {
candidate = Point(x: Int(arc4random_uniform(10)), y: Int(arc4random_uniform(10)))
}
live.append(candidate)
}
或者您可以像这样使用元组
var live: [(Int, Int)] = []
for _ in 0..<10{
var j = Int(arc4random_uniform(10))
var k = Int(arc4random_uniform(10))
while live.contains({$0 == (j, k)}) {
j = Int(arc4random_uniform(10))
k = Int(arc4random_uniform(10))
}
live.append((j,k))
}
根据您的问题大小,构建所有可能值的数组可能更为理想,然后在每次需要新的随机点集时随机播放并获取第一个X
元素。您可以进一步优化它,但代码看起来类似于:
var possibleValues: [Point] = []
for x in 0..<5 {
for y in 0..<5 {
possibleValues.append(Point(x: x, y: y))
}
}
func randomPoints(numberOfPoints: Int) -> [Point] {
// shuffle original array without changing it
let shuffled = possibleValues.sorted { _ in arc4random_uniform(10) > 5 }
// take first X elements
return Array(shuffled[0..<numberOfPoints])
}
randomPoints(numberOfPoints: 10)
您可以进一步优化此解决方案,但需要了解有关数据集的更多信息。希望这有帮助