從我明白你的問題,你想生成二維點的數組排除重複,您可以使用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))
}
根據你的問題的大小,建立一個所有可能的值的數組可能是最優的,然後洗牌並採取冷杉每當你需要一組新的隨機點時,您可以進一步優化它,但code'd類似於:
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)
你甚至可以進一步優化該解決方案但會需要更多地瞭解你的數據集。希望這可以幫助
是的,你是對的,我會更新我的示例代碼 –
我寫了幾乎相同的代碼,所以upvoted! :-) – vacawama
var live = Array>() –