2016-07-04 65 views
1

我想說,如果某些2d數組包含「點」格式[Int,Int],則重新生成隨機數,不計算迭代次數。Swift - 聲明2d數組包含

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 
     } 
    } 

回答

2

從我明白你的問題,你想生成二維點的數組排除重複,您可以使用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) 

你甚至可以進一步優化該解決方案但會需要更多地瞭解你的數據集。希望這可以幫助

+0

是的,你是對的,我會更新我的示例代碼 –

+1

我寫了幾乎相同的代碼,所以upvoted! :-) – vacawama

+0

var live = Array >() –