0

I'm trying to delete duplicate elements of type [(Int,Int)] from an array, then I'm trying to delete an array of elements of same type from parent array. This is how I do it.

func filterDuplicatesFrom(var buttonArray:[(Int,Int)]) ->[(Int,Int)]
    {
        var i: Int = 0, j:Int = 0
        var elementToDelete:[Int] = []
        for (i=0; i<buttonArray.count-1; i++)
        {
            for (j=i+1; j<buttonArray.count; j++)
            {
                if buttonArray[j].0 == buttonArray[i].0 &&  buttonArray[j].1 == buttonArray[i].1
                {
                    if elementToDelete.contains(j)
                    {
                        elementToDelete.append(j)
                    }
                }
            }
        }

        buttonArray.removeAtIndices(elementToDelete)
    }

func deletePoints(var deleteList:[(Int,Int)],var buttonArray:[(Int,Int)]) ->[(Int,Int)]
{

    var i: Int = 0, j:Int = 0
    var elementToDelete:[Int] = []
    for (i=0; i<buttonArray.count; i++)
    {
        for (j=0; j<deleteList.count; j++)
        {
            if deleteList[j].0 == buttonArray[i].0 &&  deleteList[j].1 == buttonArray[i].1
            {
                if elementToDelete.contains(i)
                {
                    elementToDelete.append(i)
                }
            }
        }
    }

    buttonArray.removeAtIndices(elementToDelete)
}

extension Array {
    mutating func removeAtIndices(incs: [Int]) {
        incs.sort(>).map { removeAtIndex($0) }
    }

This seems to work, but I wonder if it would effect the performance for large number of data. Is there a better way to do this? or what I've done is correct?

1 Answer 1

2

You could replace the tuple with a struct that conforms to Hashable protocol.

struct Button: Hashable {
    ...
}

Then if you have an array of instances of this struct you can use Sets to filter duplicates and subtract one set from the other. Sets are a collection of unordered unique elements.

/// remove duplicates (create a set)

func filterDuplicatesFrom(buttonArray:[Button]) -> Set<Button> {
    return Set(buttonArray)
}

/// delete

func deletePoints(deleteList:[Button], buttonArray:[Button]) -> Set<Button> {
    return Set(buttonArray).subtract(Set(deleteList))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.