Sobes.tech
Junior — Middle

Kā jūs izveidojat savu vārdnīcas īstenojumu?

sobes.tech AI

Atbilde no AI

Lai izveidotu savu vārdnīcas (dictionary) realizāciju iOS uz Swift, var izmantot datu struktūru, kas balstīta uz haštabulu. Galvenā ideja ir glabāt atslēgas-vērtības pārus masīvā, kur katrs grozs satur elementu sarakstu ar vienādu haškodu (kolīziju risināšanai).

Vienkāršas vārdnīcas realizācijas piemērs, izmantojot masīvu un ķēdes:

struct MyDictionary<Key: Hashable, Value> {
    private typealias Element = (key: Key, value: Value)
    private var buckets: [[Element]]
    private let capacity: Int

    init(capacity: Int = 16) {
        self.capacity = capacity
        self.buckets = Array(repeating: [], count: capacity)
    }

    private func index(forKey key: Key) -> Int {
        return abs(key.hashValue) % capacity
    }

    mutating func set(value: Value, forKey key: Key) {
        let index = self.index(forKey: key)
        // Pārbaudām, vai jau ir elements ar šo atslēgu
        if let i = buckets[index].firstIndex(where: { $0.key == key }) {
            buckets[index][i].value = value
        } else {
            buckets[index].append((key, value))
        }
    }

    func get(forKey key: Key) -> Value? {
        let index = self.index(forKey: key)
        return buckets[index].first(where: { $0.key == key })?.value
    }
}

// Lietošana:
var dict = MyDictionary<String, Int>()
dict.set(value: 42, forKey: "answer")
print(dict.get(forKey: "answer") ?? "nav atrasts")  // 42

Šāda vārdnīca atbalsta pamata operācijas, piemēram, ievietošanu un meklēšanu. Uzlabotai realizācijai var pievienot dzēšanu, dinamisku paplašināšanu, uzlabotu kolīziju apstrādi un citus uzlabojumus.