From 65f5146dc272da0424b5fa3360dc59c3bec66c6a Mon Sep 17 00:00:00 2001 From: "github-classroom[bot]" <66690702+github-classroom[bot]@users.noreply.github.com> Date: Tue, 11 May 2021 18:00:11 +0000 Subject: [PATCH 1/3] Setting up GitHub Classroom Feedback From 804ea642cbc82758ffcf2dab390703c67c66f287 Mon Sep 17 00:00:00 2001 From: Varvara Korneeva Date: Sat, 29 May 2021 00:23:03 +0300 Subject: [PATCH 2/3] hash table --- src/hash_table.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/hash_table.cpp b/src/hash_table.cpp index a581cb3..92e8e45 100644 --- a/src/hash_table.cpp +++ b/src/hash_table.cpp @@ -18,26 +18,61 @@ namespace itis { } // Tip: allocate hash-table buckets + buckets_.resize(capacity); } std::optional HashTable::Search(int key) const { // Tip: compute hash code (index) and use linear search + int index = hash(key); + for(auto bucket: buckets_[index]){ + if(bucket.first == key) return bucket.second; + } return std::nullopt; } void HashTable::Put(int key, const std::string &value) { // Tip 1: compute hash code (index) to determine which bucket to use // Tip 2: consider the case when the key exists (read the docs in the header file) + int index = hash(key); + std::pair bucket (key, value); + for(auto pair: buckets_[index]){ + if (pair.empty()) { + pair.push_back(bucket); + num_keys_++; + } + + else { + pair.second = value; + } + } if (static_cast(num_keys_) / buckets_.size() >= load_factor_) { // Tip 3: recompute hash codes (indices) for key-value pairs (create a new hash-table) // Tip 4: use utils::hash(key, size) to compute new indices for key-value pairs + std::vector new_buckets_; + new_buckets_.resize(num_keys_*kGrowthCoefficient); + for(auto bucket: buckets_){ + for(auto pair: bucket) { + int index = utils::hash(pair.first, static_cast(new_buckets_.size())); + new_buckets_[index].push_back(pair); + } + } + buckets_.clear(); + buckets_ = new_buckets_; } } std::optional HashTable::Remove(int key) { // Tip 1: compute hash code (index) to determine which bucket to use // TIp 2: find the key-value pair to remove and make a copy of value to return + int index = hash(key); + for(auto pair: buckets_[index]){ + if(pair.first == key){ + auto value = pair.second; + buckets_[index].remove(pair); + return value; + } + } return std::nullopt; } From faf4eacf218d78ae77c51a5b768005e324de967e Mon Sep 17 00:00:00 2001 From: Varvara Korneeva Date: Sat, 29 May 2021 00:29:47 +0300 Subject: [PATCH 3/3] hash table --- src/hash_table.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/hash_table.cpp b/src/hash_table.cpp index 92e8e45..e52aacf 100644 --- a/src/hash_table.cpp +++ b/src/hash_table.cpp @@ -70,6 +70,7 @@ namespace itis { if(pair.first == key){ auto value = pair.second; buckets_[index].remove(pair); + num_keys_--; return value; } }