I want to remove duplicate ranges of 3 within an array:
let array = [
"string-1",
"string-2",
"string-3",
"string-4",
"string-5",
"string-3",
"string-4",
"string-5",
"string-6",
"string-7",
"string-8",
"string-9",
"string-10",
"string-11",
"string-9",
"string-10",
"string-11",
"string-12"
]
The patterns:
"string-3",
"string-4",
"string-5"
and
"string-9",
"string-10",
"string-11"
appear twice.
How would I detect and remove them?
func removeDuplicateSequences(from array: [String]) -> [String] {
var result = array
var indicesToRemove = Set<Int>()
// Check for every sequence of three elements in the array
for i in 0..<result.count - 2 {
let currentSequence = Array(result[i...i+2])
// Only proceed if this sequence hasn't been marked for removal
if !indicesToRemove.contains(i) {
for j in i+1..<result.count - 2 {
let nextSequence = Array(result[j...j+2])
// If a duplicate sequence is found, mark its indices for removal
if currentSequence == nextSequence {
indicesToRemove.insert(j)
indicesToRemove.insert(j+1)
indicesToRemove.insert(j+2)
}
}
}
}
// Remove elements in reverse order to avoid index out of range errors
for index in indicesToRemove.sorted(by: >) {
result.remove(at: index)
}
return result
}
This fiction meets these requirements. I am not aware of any native version.