0

I have the following situation where I need to remove some elements from an array. I have an array with elements as followed:

[
    "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"
] 

I need to transform this into an array with only these elements:

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

IN the above example, elements "white & blue" and "blue & white" need to be treated as being the same, keeping only one of them and removing the other.

I have not found a way that works. How I can do it?

cwilliamsz
  • 718
  • 9
  • 20
  • This has too many parts and is too broad as it currently is. On a high level you need to parse the strings, standardize the resulting output, filter out duplicates and return the result to this original format. You should figure out which of these is causing you trouble and ask individual questions about them. – Tristan Burnside Jul 15 '17 at 15:07

1 Answers1

2

For equality described as: the "white & blue" and "blue & white" elements need to be treated as being the same, the equality defined for Set works well.

For preparation:

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

(Assuming each color name appears at most once in each element.)

And one more Set, when removing duplicate from an Array, Set is very useful.

removing duplicate elements from an array

So, you can write something like this:

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"]
OOPer
  • 47,149
  • 6
  • 107
  • 142