ironRoei
ironRoei

Reputation: 2209

Swift - filter with n complexity

So i want to filter an array with n complexity. The objective is to recognise the duplicate card(by id) and keep the card with status "a" and add him to the array(filter out the duplicate with status that different from "a") The code i have is as follow:

struct Card {
 var id:String
 var status:String

init(id:String, status:String) {
    self.id = id
    self.status = status
 }
}

let card1 = Card(id: "123", status: "a")
let card3 = Card(id: "43", status: "a")
let card4 = Card(id: "45", status: "a")
let card2 = Card(id: "123", status: "b")
let card5 = Card(id: "1234", status: "c")


let arrr = [card1,card3,card4,card2,card5]




func getCreditCardsOnly(creditCardsData:[Card]) -> [Card] {
var filter = [Card]()

for card in creditCardsData {
    if !filter.contains(where: {$0.id == card.id && $0.status != "b"}) {
        filter.append(card)
    }
}

 return filter
}

the output is:

Card(id: "123", status: "a"), Card(id: "43", status: "a"), Card(id: "45", status: "a"), Card(id: "1234", status: "c")]

As wanted, yet the complexity is n^2. Is there a way to lower the complexity?

Upvotes: 1

Views: 260

Answers (1)

PGDev
PGDev

Reputation: 24341

Use Dictionary's init(grouping:by:) and filter(_:) to get the expected result, i.e.

let result = Dictionary(grouping: arrr, by: { $0.status }).values.filter({ $0.first?.status != "b"})
print(result)

The above code has complexity O(n).

Upvotes: 1

Related Questions