0

For context I'm creating my own hashmap in swift.

I've got an element and I'm storing the elements in buckets which is an array of arrays

struct Element {
    var key: Int
    var value: Int
}

class MyHashMap {
    var buckets : [[Element]] = [[]]

    init() {
        buckets = [Array(repeating: Element(key: -1, value: -1), count: 2)]
        buckets.append([Element(key: 3, value: 4)])
    }

}

I want to remove all the buckets where the key is -1 and I'm struggling.

Flatmap does not return the right type i.e.

hashmap.buckets.flatMap{$0}.filter{$0.key != -1}

is incorrect.

How can I remove all of the buckets with key -1?

1
  • If any of the answers has solved your issue then please mark it as accepted or give some feedback why this isn't resolved yet. Commented Jun 1, 2019 at 7:14

2 Answers 2

1

Map the outer array to a new array of arrays, where from the inner array only the elements with key != -1 are preserved. I would make this a method of the MyHashMap class:

class MyHashMap {
    // ...

    func compactBuckets() {
        buckets = buckets.map { $0.filter { $0.key != -1 }}
    }
}

Alternatively (and possibly more efficient), with a loop over the indices of the outer array:

    func compactBuckets() {
        for i in buckets.indices {
            buckets[i].removeAll(where: { $0.key == -1 })
        }
    }

In either case you may additionally want to remove empty inner arrays from the outer array:

        buckets.removeAll(where: { $0.isEmpty })
Sign up to request clarification or add additional context in comments.

4 Comments

Doing print(hashmap.buckets.count) after either of your suggestions will return 2 instead of 1. There seems to be an empty array left in the buckets array. Notice what it says in the question "I want to remove all the buckets where the key is -1"
@JoakimDanielson: I interpreted the problem as “remove all entries with key=-1 from the nested array,” not as “remove all inner arrays which have any entry with key=-1,” but I may be wrong of course. – You were right about the first point.
Hopefully OP will let us know which interpretation is right.
It's a hashmap. Therefore remove all entries with key=-1
0

You can use removeAll where you filter with contains for the buckets

hashmap.buckets.removeAll { $0.contains { $0.key == -1 } }

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.