2017-09-06 7 views
2

arrayarrayです。intです。したがって、let pairs:[[Int]]です。Swift 3同様のオブジェクトの抽出

私は同様の要素を抽出するエレガントな方法を探しています。私はかつてのような[1,2]以上発生任意の配列を抽出したい[ [1,2], [4,6], [1,2] ]

:変数私のペアのようなものが含まれている可能性が例えば

。 例では[ [1,2], [4,6], [1,2], [3,7], [4,6] ][1,2][4,6]の両方を抽出したいと思います。

これは最初は些細なようでしたが、私が行ったたびに、多くの "ヘルパーアレイ"とネストされた "forループ"が非常に扱いにくくなりました。スウィフトではもっと簡単な方法でしょうか?ここで

おかげ

答えて

0

ただ1つのヘルパー辞書と一つのループを使用した方法:

let pairs = [[1,2], [4,6], [1,2]] // The original array 
var pairCount = [NSArray : Int]() // This is helper dictionary. The key is the array, the value is - how much time it appears in the source array. I use NSArray because swift array does not conform to Hashable protocol. 
var newPairs = [[Int]]() 

for pair in pairs { // Iterate over our pairs 
    var count: Int = pairCount[pair as NSArray] ?? 0 // If we already have a pair in our dictionary get count of it in array otherwise het 0 

    count += 1 // increase counter 

    pairCount[pair as NSArray] = count // save in dictionary 
} 

let pairsWithCountMoreThanOne = pairCount.flatMap({$1 > 1 ? $0 : nil}) // here we get the result 

for pair in pairsWithCountMoreThanOne { // Just print it 
    print("\(pair)") 
} 

このコードは、大きな配列やラージオブジェクトのための効率的なメモリではないかもしれないが、それは本当に簡単です。

0

下記をご確認ください:

let pairs = [ [1,2], [4,6], [1,2], [3,7], [4,6], [3,5], [4,6] ] 
var repeats = [[Int]]() 

pairs.forEach { (i) in 
    let count = (pairs.filter{ return $0 == i }).count 
    if count > 1 { 
     if !repeats.contains(where: { (pair) -> Bool in 
      return pair == i 
     }) { 
      repeats.append(i) 
     } 
    } 
} 
print(repeats) // Output is : [[1, 2], [4, 6]] 
関連する問題