Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions hash_map/ChainingBackend.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#ifndef CP_DATA_STRUCTURES_CHAINING_HPP
#define CP_DATA_STRUCTURES_CHAINING_HPP

#pragma once

#include <algorithm>
#include <list>
#include <utility>
#include <vector>

#include "IBackend.hpp"
#include "UniversalHash.hpp"


namespace hashmap::detail {
template<typename K, typename V>
class ChainingBackend : public IBackend<K, V> {
public:
explicit ChainingBackend(size_t initial_size, double max_load_factor = 1.0)
: buckets_(std::max<size_t>(initial_size, 1)),
hasher_(std::max<size_t>(initial_size, 1)),
count_(0),
max_load_factor_(max_load_factor) {
}

void Insert(const K &key, const V &value) override {
if (LoadFactor() >= max_load_factor_) {
Grow(buckets_.size() * 2);
}
auto &bucket = buckets_[BucketIndex(key)];
for (auto &kv: bucket) {
if (kv.first == key) {
kv.second = value;
return;
}
}
bucket.emplace_back(key, value);
++count_;
}

std::optional<V> Search(const K &key) const override {
const auto &bucket = buckets_[BucketIndex(key)];
for (const auto &kv: bucket) {
if (kv.first == key) return kv.second;
}
return std::nullopt;
}

bool Delete(const K &key) override {
auto &bucket = buckets_[BucketIndex(key)];
for (auto it = bucket.begin(); it != bucket.end(); ++it) {
if (it->first == key) {
bucket.erase(it);
--count_;
return true;
}
}
return false;
}

[[nodiscard]] size_t Size() const override { return count_; }
[[nodiscard]] size_t Capacity() const override { return buckets_.size(); }

private:
size_t BucketIndex(const K &key) const { return static_cast<size_t>(hasher_(key)); }

[[nodiscard]] double LoadFactor() const {
return static_cast<double>(count_ + 1) / static_cast<double>(buckets_.size());
}

void Grow(size_t new_size) {
std::vector<std::list<std::pair<K, V> > > new_buckets(new_size);
hasher_.Rehash(new_size);
for (auto &bucket: buckets_) {
for (auto &kv: bucket) {
new_buckets[static_cast<size_t>(hasher_(kv.first))].push_back(std::move(kv));
}
}
buckets_ = std::move(new_buckets);
}

std::vector<std::list<std::pair<K, V> > > buckets_;
KeyHasher<K> hasher_;
size_t count_;
double max_load_factor_;
};
}

#endif //CP_DATA_STRUCTURES_CHAINING_HPP
55 changes: 55 additions & 0 deletions hash_map/DirectAddressTable.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#ifndef CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP
#define CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP

#pragma once

#include <optional>
#include <stdexcept>
#include <vector>

namespace hashmap {
template <typename V>
class DirectAddressTable {
public:
explicit DirectAddressTable(size_t universe_size)
: slots_(universe_size), count_(0) {}

void Insert(size_t key, const V& value) {
CheckRange(key);
if (!slots_[key].has_value()) {
++count_;
}
slots_[key] = value;
}

std::optional<V> Search(size_t key) const {
CheckRange(key);
return slots_[key];
}

bool Delete(size_t key) {
CheckRange(key);
if (!slots_[key].has_value()) {
return false;
}
slots_[key].reset();
--count_;
return true;
}

size_t Size() const { return count_; }
size_t UniverseSize() const { return slots_.size(); }

private:
void CheckRange(size_t key) const {
if (key >= slots_.size()) {
throw std::out_of_range("key is outside of the table universe");
}
}

std::vector<std::optional<V>> slots_;
size_t count_;
};
}

#endif //CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP
58 changes: 58 additions & 0 deletions hash_map/HashMap.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#ifndef CP_DATA_STRUCTURES_HASHMAP_HPP
#define CP_DATA_STRUCTURES_HASHMAP_HPP

#pragma once
#include <memory>
#include <stdexcept>

#include "ChainingBackend.hpp"
#include "OpenAddressingBackend.hpp"

namespace hashmap {

enum class Strategy {
Chaining,
LinearProbing,
QuadraticProbing,
DoubleHashing,
};

template <typename K, typename V>
class HashMap {
public:
explicit HashMap(Strategy strategy, size_t initial_capacity = 16)
: backend_(MakeBackend(strategy, initial_capacity)) {}

void Insert(const K& key, const V& value) { backend_->Insert(key, value); }
[[nodiscard]] std::optional<V> Search(const K& key) const { return backend_->Search(key); }
[[nodiscard]] bool Delete(const K& key) { return backend_->Delete(key); }

[[nodiscard]] size_t Size() const { return backend_->Size(); }
[[nodiscard]] size_t Capacity() const { return backend_->Capacity(); }
[[nodiscard]] double LoadFactor() const {
return static_cast<double>(Size()) / static_cast<double>(Capacity());
}

private:
[[nodiscard]] static std::unique_ptr<detail::IBackend<K, V>> MakeBackend(Strategy strategy, size_t initial_capacity) {
switch (strategy) {
case Strategy::Chaining:
return std::make_unique<detail::ChainingBackend<K, V>>(initial_capacity);
case Strategy::LinearProbing:
return std::make_unique<detail::OpenAddressingBackend<K, V>>(initial_capacity, ProbeStrategy::Linear);
case Strategy::QuadraticProbing:
return std::make_unique<detail::OpenAddressingBackend<K, V>>(initial_capacity, ProbeStrategy::Quadratic);
case Strategy::DoubleHashing:
return std::make_unique<detail::OpenAddressingBackend<K, V>>(initial_capacity, ProbeStrategy::Double);
}
throw std::invalid_argument("unknown strategy");
}

std::unique_ptr<detail::IBackend<K, V>> backend_;
};

}

#endif //CP_DATA_STRUCTURES_HASHMAP_HPP


24 changes: 24 additions & 0 deletions hash_map/IBackend.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#ifndef CP_DATA_STRUCTURES_IBACKEND_HPP
#define CP_DATA_STRUCTURES_IBACKEND_HPP

#pragma once

#include <optional>


namespace hashmap::detail {
template <typename K, typename V>
class IBackend {
public:
virtual ~IBackend() = default;

virtual void Insert(const K& key, const V& value) = 0;
virtual std::optional<V> Search(const K& key) const = 0;
virtual bool Delete(const K& key) = 0;

[[nodiscard]] virtual size_t Size() const = 0;
[[nodiscard]] virtual size_t Capacity() const = 0;
};
}

#endif //CP_DATA_STRUCTURES_IBACKEND_HPP
164 changes: 164 additions & 0 deletions hash_map/OpenAddressingBackend.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
#ifndef CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H
#define CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H

#pragma once

#include <memory>
#include <vector>

#include "IBackend.hpp"
#include "UniversalHash.hpp"

namespace hashmap {
enum class ProbeStrategy {
Linear, // idx = (base + i) % size
Quadratic, // idx = (base + i*i) % size
Double, // idx = (base + i*step) % size
};

namespace detail {
template<typename K, typename V>
class OpenAddressingBackend : public IBackend<K, V> {
public:
OpenAddressingBackend(size_t initial_size, ProbeStrategy strategy)
: size_(std::max<size_t>(initial_size, 1)),
count_(0),
strategy_(strategy),
h1_(size_),
h2_(size_) {
slots_.resize(size_);
}

void Insert(const K &key, const V &value) override {
if (LoadFactor() >= kMaxLoadFactor) {
Grow(size_ * 2);
}
InsertInto(key, value);
}

std::optional<V> Search(const K &key) const override {
const size_t base = BaseHash(key);
const size_t step = StepHash(key);

for (size_t i = 0; i < size_; ++i) {
const size_t idx = Probe(base, step, i);
const Node *node = slots_[idx].get();
if (node == nullptr) return std::nullopt;
if (!node->deleted && node->key == key) return node->value;
}
return std::nullopt;
}

bool Delete(const K &key) override {
const size_t base = BaseHash(key);
const size_t step = StepHash(key);

for (size_t i = 0; i < size_; ++i) {
const size_t idx = Probe(base, step, i);
Node *node = slots_[idx].get();
if (node == nullptr) return false;
if (!node->deleted && node->key == key) {
node->deleted = true;
--count_;
return true;
}
}
return false;
}

[[nodiscard]] size_t Size() const override { return count_; }
[[nodiscard]] size_t Capacity() const override { return size_; }

private:
struct Node {
K key;
V value;
bool deleted;
};

static constexpr double kMaxLoadFactor = 0.7;

[[nodiscard]] double LoadFactor() const {
return static_cast<double>(count_ + 1) / static_cast<double>(size_);
}

size_t BaseHash(const K &key) const { return static_cast<size_t>(h1_(key)); }

size_t StepHash(const K &key) const {
if (size_ == 1) return 1;
size_t step = static_cast<size_t>(h2_(key)) % (size_ - 1);
return step + 1;
}

[[nodiscard]] size_t Probe(size_t base, size_t step, size_t i) const {
switch (strategy_) {
case ProbeStrategy::Linear:
return (base + i) % size_;
case ProbeStrategy::Quadratic:
return (base + i * i) % size_;
case ProbeStrategy::Double:
return (base + i * step) % size_;
}
return (base + i) % size_;
}

void InsertInto(const K &key, const V &value) {
const size_t base = BaseHash(key);
const size_t step = StepHash(key);
long long first_free = -1;

for (size_t i = 0; i < size_; ++i) {
const size_t idx = Probe(base, step, i);
Node *node = slots_[idx].get();

if (node == nullptr) {
if (first_free == -1) first_free = static_cast<long long>(idx);
break;
}
if (node->deleted) {
if (first_free == -1) first_free = static_cast<long long>(idx);
continue;
}
if (node->key == key) {
node->value = value;
return;
}
}

if (first_free == -1) {
Grow(size_ * 2);
InsertInto(key, value);
return;
}

slots_[static_cast<size_t>(first_free)] = std::make_unique<Node>(Node{key, value, false});
++count_;
}

void Grow(size_t new_size) {
std::vector<std::unique_ptr<Node> > old_slots = std::move(slots_);
size_ = new_size;
slots_.clear();
slots_.resize(size_);
count_ = 0;
h1_.Rehash(size_);
h2_.Rehash(size_);

for (auto &node: old_slots) {
if (node && !node->deleted) {
InsertInto(node->key, node->value);
}
}
}

std::vector<std::unique_ptr<Node> > slots_;
size_t size_;
size_t count_;
ProbeStrategy strategy_;
KeyHasher<K> h1_;
KeyHasher<K> h2_;
};
}
}

#endif //CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H
Loading