Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove duplicate ranges found within array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"string-9",
"string-10",
"string-11"

appear twice.

How would I detect and remove them?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading