2017-07-15 178 views
0

我有以下情況,我需要從數組中刪除一些元素。我有元素的數組如下:從數組中刪除一些元素

[ 
    "white & blue", "white & red", "white & black", 
    "blue & white", "blue & red", "blue & black", 
    "red & white", "red & blue", "red & black", 
    "black & white", "black & blue", "black & red", 
    "white", "blue", "red", "black", 
    "white & blue & red & black" 
] 

我需要僅這些要素轉換到這一點的數組:在上面的例子

[ 
    "white & blue", "white & red", "white & black", 
    "blue & red", "blue & black", 
    "red & black", 
    "white", "blue", "red", "black", 
    "white & blue & red & black" 
] 

,元件"white & blue""blue & white"需要被視爲是一樣的,只保留其中一個並刪除另一個。

我還沒找到有效的方法。我如何做到這一點?

+0

這有太多的部件和過於寬泛,因爲它是目前。在高層次上,您需要解析字符串,將結果輸出標準化,過濾掉重複項並將結果返回到原始格式。你應該弄清楚哪些是造成你的麻煩,並提出關於他們的個別問題。 –

回答

2

對於平等描述爲:「白色&藍」「藍白色&」元素需要被視爲是相同的,在平等Set作品定義明確的。

爲了製備:

extension String { 
    var colorNameSet: Set<String> { 
     let colorNames = self.components(separatedBy: "&") 
      .map {$0.trimmingCharacters(in: .whitespaces)} 
     return Set(colorNames) 
    } 
} 

"white & blue".colorNameSet == "blue & white".colorNameSet //== true 

(假設每個顏色名稱將出現在每個元素最多一次。)

還有一Set,除去從數組複製時,Set是非常有用的。

removing duplicate elements from an array

所以,你可以寫這樣的事情:

let originalArray = [ 
    "white & blue", "white & red", "white & black", "blue & white", 
    "blue & red", "blue & black", "red & white", "red & blue", 
    "red & black", "black & white", "black & blue", "black & red", 
    "white", "blue", "red", "black", "white & blue & red & black"] 

func filterDuplicateColorNameSet(_ originalArray: [String]) -> [String] { 
    var foundColorNameSets: Set<Set<String>> = [] 
    let filteredArray = originalArray.filter {element in 
     let (isNew,_) = foundColorNameSets.insert(element.colorNameSet) 
     return isNew 
    } 
    return filteredArray 
} 

print(filterDuplicateColorNameSet(originalArray)) 
//->["white & blue", "white & red", "white & black", "blue & red", "blue & black", "red & black", "white", "blue", "red", "black", "white & blue & red & black"] 
+0

非常感謝,這工作完美。 – cwilliamsz