Sobes.tech
Junior — Middle

Kaip kuriate savo žodyno įgyvendinimą?

sobes.tech AI

Atsakymas iš AI

Sukurti savo žodyno (dictionary) įgyvendinimą iOS naudojant Swift, galite naudoti duomenų struktūrą, pagrįstą maišos lentele. Pagrindinė idėja yra saugoti poras raktas-reikšmė masyve, kur kiekvienas maišymo dėžutė (bucket) turi sąrašą elementų su tuo pačiu maišos kodu (sprendžiant kolizijas).

Pavyzdys paprasto žodyno įgyvendinimo naudojant masyvą ir grandines:

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)
        // Patikrinkite, ar jau yra elementas su šiuo raktu
        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
    }
}

// Naudojimas:
var dict = MyDictionary<String, Int>()
dict.set(value: 42, forKey: "answer")
print(dict.get(forKey: "answer") ?? "not found")  // 42

Šis žodynas palaiko pagrindines įterpimo ir paieškos operacijas. Pažangesnei įgyvendinimui galima pridėti ištrynimą, dinaminį išplėtimą, patobulintą kolizijų valdymą ir kt.