From c0c36406cadd19710d3a8b35253f8a60faf0dff9 Mon Sep 17 00:00:00 2001 From: cloudnative0x0 <> Date: Tue, 11 Aug 2026 22:49:49 +0300 Subject: [PATCH 1/2] Hash map added. --- hash_map/ChainingBackend.hpp | 89 ++++++++++++++++ hash_map/DirectAddressTable.hpp | 55 ++++++++++ hash_map/HashMap.hpp | 58 ++++++++++ hash_map/IBackend.hpp | 24 +++++ hash_map/OpenAddressingBackend.hpp | 164 +++++++++++++++++++++++++++++ hash_map/UniversalHash.hpp | 76 +++++++++++++ 6 files changed, 466 insertions(+) create mode 100644 hash_map/ChainingBackend.hpp create mode 100644 hash_map/DirectAddressTable.hpp create mode 100644 hash_map/HashMap.hpp create mode 100644 hash_map/IBackend.hpp create mode 100644 hash_map/OpenAddressingBackend.hpp create mode 100644 hash_map/UniversalHash.hpp diff --git a/hash_map/ChainingBackend.hpp b/hash_map/ChainingBackend.hpp new file mode 100644 index 0000000..a4beea5 --- /dev/null +++ b/hash_map/ChainingBackend.hpp @@ -0,0 +1,89 @@ +#ifndef CP_DATA_STRUCTURES_CHAINING_HPP +#define CP_DATA_STRUCTURES_CHAINING_HPP + +#pragma once + +#include +#include +#include +#include + +#include "IBackend.hpp" +#include "UniversalHash.hpp" + + +namespace hashmap::detail { + template + class ChainingBackend : public IBackend { + public: + explicit ChainingBackend(size_t initial_size, double max_load_factor = 1.0) + : buckets_(std::max(initial_size, 1)), + hasher_(std::max(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 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(hasher_(key)); } + + [[nodiscard]] double LoadFactor() const { + return static_cast(count_ + 1) / static_cast(buckets_.size()); + } + + void Grow(size_t new_size) { + std::vector > > new_buckets(new_size); + hasher_.Rehash(new_size); + for (auto &bucket: buckets_) { + for (auto &kv: bucket) { + new_buckets[static_cast(hasher_(kv.first))].push_back(std::move(kv)); + } + } + buckets_ = std::move(new_buckets); + } + + std::vector > > buckets_; + KeyHasher hasher_; + size_t count_; + double max_load_factor_; + }; +} + +#endif //CP_DATA_STRUCTURES_CHAINING_HPP diff --git a/hash_map/DirectAddressTable.hpp b/hash_map/DirectAddressTable.hpp new file mode 100644 index 0000000..b8f1e47 --- /dev/null +++ b/hash_map/DirectAddressTable.hpp @@ -0,0 +1,55 @@ +#ifndef CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP +#define CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP + +#pragma once + +#include +#include +#include + +namespace hashmap { + template + 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 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> slots_; + size_t count_; + }; +} + +#endif //CP_DATA_STRUCTURES_DIRECT_ADDRESS_TABLE_HPP diff --git a/hash_map/HashMap.hpp b/hash_map/HashMap.hpp new file mode 100644 index 0000000..a07c970 --- /dev/null +++ b/hash_map/HashMap.hpp @@ -0,0 +1,58 @@ +#ifndef CP_DATA_STRUCTURES_HASHMAP_HPP +#define CP_DATA_STRUCTURES_HASHMAP_HPP + +#pragma once +#include +#include + +#include "ChainingBackend.hpp" +#include "OpenAddressingBackend.hpp" + +namespace hashmap { + +enum class Strategy { + Chaining, + LinearProbing, + QuadraticProbing, + DoubleHashing, +}; + +template +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 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(Size()) / static_cast(Capacity()); + } + +private: + [[nodiscard]] static std::unique_ptr> MakeBackend(Strategy strategy, size_t initial_capacity) { + switch (strategy) { + case Strategy::Chaining: + return std::make_unique>(initial_capacity); + case Strategy::LinearProbing: + return std::make_unique>(initial_capacity, ProbeStrategy::Linear); + case Strategy::QuadraticProbing: + return std::make_unique>(initial_capacity, ProbeStrategy::Quadratic); + case Strategy::DoubleHashing: + return std::make_unique>(initial_capacity, ProbeStrategy::Double); + } + throw std::invalid_argument("unknown strategy"); + } + + std::unique_ptr> backend_; +}; + +} + +#endif //CP_DATA_STRUCTURES_HASHMAP_HPP + + diff --git a/hash_map/IBackend.hpp b/hash_map/IBackend.hpp new file mode 100644 index 0000000..32cb866 --- /dev/null +++ b/hash_map/IBackend.hpp @@ -0,0 +1,24 @@ +#ifndef CP_DATA_STRUCTURES_IBACKEND_HPP +#define CP_DATA_STRUCTURES_IBACKEND_HPP + +#pragma once + +#include + + +namespace hashmap::detail { + template + class IBackend { + public: + virtual ~IBackend() = default; + + virtual void Insert(const K& key, const V& value) = 0; + virtual std::optional 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 diff --git a/hash_map/OpenAddressingBackend.hpp b/hash_map/OpenAddressingBackend.hpp new file mode 100644 index 0000000..8a400f3 --- /dev/null +++ b/hash_map/OpenAddressingBackend.hpp @@ -0,0 +1,164 @@ +#ifndef CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H +#define CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H + +#pragma once + +#include +#include + +#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 + class OpenAddressingBackend : public IBackend { + public: + OpenAddressingBackend(size_t initial_size, ProbeStrategy strategy) + : size_(std::max(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 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(count_ + 1) / static_cast(size_); + } + + size_t BaseHash(const K &key) const { return static_cast(h1_(key)); } + + size_t StepHash(const K &key) const { + if (size_ == 1) return 1; + size_t step = static_cast(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(idx); + break; + } + if (node->deleted) { + if (first_free == -1) first_free = static_cast(idx); + continue; + } + if (node->key == key) { + node->value = value; + return; + } + } + + if (first_free == -1) { + Grow(size_ * 2); + InsertInto(key, value); + return; + } + + slots_[static_cast(first_free)] = std::make_unique(Node{key, value, false}); + ++count_; + } + + void Grow(size_t new_size) { + std::vector > 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 > slots_; + size_t size_; + size_t count_; + ProbeStrategy strategy_; + KeyHasher h1_; + KeyHasher h2_; + }; + } +} + +#endif //CP_DATA_STRUCTURES_OPEN_ADDRESSING_BACKEND_H diff --git a/hash_map/UniversalHash.hpp b/hash_map/UniversalHash.hpp new file mode 100644 index 0000000..31299c5 --- /dev/null +++ b/hash_map/UniversalHash.hpp @@ -0,0 +1,76 @@ +#ifndef CP_DATA_STRUCTURES_UNIVERSAL_HASH_HPP +#define CP_DATA_STRUCTURES_UNIVERSAL_HASH_HPP + +#pragma once + +#include +#include +#include +#include + +namespace hashmap { + class UniversalHash { + public: + explicit UniversalHash(uint64_t table_size, uint64_t prime = kDefaultPrime) + : table_size_(table_size), prime_(prime) { + if (table_size_ == 0) { + throw std::invalid_argument("table_size must be > 0"); + } + Reseed(); + } + + uint64_t operator()(uint64_t x) const { + uint64_t xm = x % prime_; + unsigned __int128 val = static_cast(a_) * xm + b_; + auto h = static_cast(val % prime_); + return h % table_size_; + } + + void Rehash(uint64_t new_table_size) { + if (new_table_size == 0) { + throw std::invalid_argument("new_table_size must be > 0"); + } + table_size_ = new_table_size; + Reseed(); + } + + [[nodiscard]] uint64_t TableSize() const { return table_size_; } + + private: + static constexpr uint64_t kDefaultPrime = (1ull << 61) - 1; + + void Reseed() { + std::random_device rd; + std::mt19937_64 gen(rd()); + std::uniform_int_distribution dist_a(1, prime_ - 1); + std::uniform_int_distribution dist_b(0, prime_ - 1); + a_ = dist_a(gen); + b_ = dist_b(gen); + } + + uint64_t table_size_; + uint64_t prime_; + uint64_t a_ = 1; + uint64_t b_ = 0; + }; + + template + class KeyHasher { + public: + explicit KeyHasher(uint64_t table_size) : uh_(table_size) { + } + + uint64_t operator()(const K &key) const { + auto x = static_cast(std::hash{}(key)); + return uh_(x); + } + + void Rehash(uint64_t new_table_size) { uh_.Rehash(new_table_size); } + [[nodiscard]] uint64_t TableSize() const { return uh_.TableSize(); } + + private: + UniversalHash uh_; + }; +} + +#endif //CP_DATA_STRUCTURES_UNIVERSAL_HASH_HPP From db8e2adab93ee774f626b5759127f64b81575a57 Mon Sep 17 00:00:00 2001 From: cloudnative0x0 <> Date: Tue, 11 Aug 2026 23:01:59 +0300 Subject: [PATCH 2/2] stress test and readme created. --- hash_map/README.md | 211 ++++++++++++++++++++++++++ hash_map/stress_test.cpp | 309 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 520 insertions(+) create mode 100644 hash_map/README.md create mode 100644 hash_map/stress_test.cpp diff --git a/hash_map/README.md b/hash_map/README.md new file mode 100644 index 0000000..9e3aeef --- /dev/null +++ b/hash_map/README.md @@ -0,0 +1,211 @@ +# HashMap + +

+ Русский ・ English +

+ +--- + +## Русский + +Хеш-таблица — структура данных, которая хранит пары ключ-значение и в среднем даёт O(1) на вставку, поиск и удаление. Цена за это — коллизии: два разных ключа почти неизбежно попадают в один и тот же слот, если ключей много, а слотов мало. Разница между реализациями хеш-таблиц — это, по сути, разница в том, как именно они разруливают эти коллизии. + +В проекте пять разных структур, объединённых общим интерфейсом `IBackend`, плюс отдельно стоящая `DirectAddressTable` для случая, когда коллизий вообще не нужно. + +### Прямая адресация — `DirectAddressTable.hpp` + +Самый простой случай: универсум ключей `U` небольшой, и можно завести массив размера `|U|`, где `T[k]` хранит значение для ключа `k` напрямую, без всякого хеширования. Это классическая прямая адресация (Кормен, Лейзерсон, Ривест, Штайн, глава 11.1). + +`slots_` — вектор `std::optional` размера `universe_size`. `Insert`, `Search`, `Delete` работают за честное O(1): просто обращение по индексу, `CheckRange` бросает исключение, если ключ вышел за границы универсума. Плата за скорость — память: таблица всегда занимает `O(|U|)`, даже если реально используется десяток ключей из миллиона. Отсюда и ограничение применимости — это не решение общего назначения, а инструмент для задач, где ключи — это, например, индексы или маленькие целые числа с известной верхней границей. + +### Универсальное хеширование — `UniversalHash.hpp` + +Проблема любой фиксированной хеш-функции в том, что для неё всегда можно подобрать входные данные, на которых она будет вырождаться в один бакет — противник (или просто неудачный набор данных) знает функцию заранее. Универсальное хеширование решает это, выбирая функцию случайно из семейства при каждом создании или ресайзе таблицы. + +Семейство здесь — классическое: + +``` +h_{a,b}(x) = ((a·x + b) mod p) mod m +``` + +где `p` — простое число, заведомо больше любого возможного значения `x` (в коде это `2^61 - 1`), `a` выбирается равномерно из `{1, ..., p-1}`, `b` — равномерно из `{0, ..., p-1}`, а `m` — размер таблицы. При каждом вызове `Reseed()` (в конструкторе и в `Rehash`) `a` и `b` перегенерируются заново через `std::mt19937_64`. + +Ключевое свойство такого семейства: для любых двух различных `x ≠ y` + +``` +Pr[h(x) = h(y)] ≤ 1/m +``` + +вероятность берётся по случайному выбору `a` и `b`, а не по входным данным. Отсюда и вся последующая математика: сколько бы раз ни запускали программу на одних и тех же ключах, для конкретного противника нет способа гарантированно устроить коллизию, потому что функция каждый раз новая. + +`KeyHasher` — обёртка поверх `UniversalHash`: сначала произвольный ключ `K` приводится к `uint64_t` через `std::hash`, затем результат прогоняется через универсальную хеш-функцию. Два разных объекта `KeyHasher` (как в открытой адресации, `h1_` и `h2_`) хешируют независимо, с разными случайными `a`, `b`. + +### Разрешение коллизий цепочками — `ChainingBackend.hpp` + +Каждый бакет или "ведро" — это `std::list>`. При коллизии элемент просто дописывается в список того же бакета, а не пытается найти себе другое место. + +- `Insert`: сначала проверяется коэффициент заполнения `(count_ + 1) / buckets_.size()`, и если он достиг `max_load_factor_` (по умолчанию 1.0), таблица удваивается заранее, до вставки. Затем — линейный проход по бакету в поисках существующего ключа (обновление значения) либо добавление нового узла в конец списка. +- `Search` и `Delete` — линейный проход по конкретному бакету. +- `Grow`: создаётся новый вектор бакетов, хешер пересевается под новый размер (`Rehash`), и все элементы старой таблицы перекладываются в новую — их бакет меняется, потому что хеш-функция теперь другая. + +Математика здесь стандартная (Кормен, глава 11.2): при равномерном хешировании и коэффициенте заполнения `α = n/m` ожидаемая длина непустой цепочки — `O(1 + α)`, и это же — ожидаемое время неуспешного поиска. Поскольку в этой реализации таблица удваивается до того, как `α` превысит 1, средняя длина цепочки никогда не растёт бесконтрольно — амортизированная стоимость операции остаётся `O(1)`, а сам ресайз, хоть и стоит `O(n)`, случается всё реже по мере роста таблицы (классический аргумент амортизационного анализа для удвоения). + +### Открытая адресация — `OpenAddressingBackend.hpp` + +Здесь коллизии разрешаются иначе: все элементы живут в одном массиве `slots_`, и при коллизии ключ ищет себе следующий свободный слот по заранее определённой последовательности проб. Максимальный коэффициент заполнения — `0.7` (`kMaxLoadFactor`), заметно ниже, чем у цепочек: при открытой адресации производительность деградирует резко при приближении `α` к 1, поэтому запас по месту нужен всегда. + +Последовательность проб задаётся как `⟨h(k,0), h(k,1), ..., h(k,m-1)⟩`, и в идеале (гипотеза равномерного хеширования) должна быть равновероятной перестановкой всех `m` индексов для каждого ключа. В коде реализованы три стратегии — `Probe(base, step, i)`: + +- **Линейное пробирование** — `idx = (base + i) mod m`. Самая дешёвая по вычислениям, но подвержена первичной кластеризации: соседние занятые слоты имеют тенденцию срастаться в длинные последовательности, потому что любой ключ, чей `base` попал внутрь такой последовательности, продолжает её же и удлиняет. +- **Квадратичное пробирование** — `idx = (base + i²) mod m`. Первичной кластеризации нет, но появляется вторичная: два ключа с одинаковым `base` идут по абсолютно одинаковой последовательности проб. Отдельная тонкость: квадратичное пробирование гарантированно обходит все `m` слотов только при определённых `m` (например, `m` — простое число вида `4k+3`, либо специальный подбор констант); при произвольном чётном `m`, как здесь после удвоения, часть слотов теоретически может быть недостижима с конкретного `base` за один проход — на практике `InsertInto` подстраховывается: если полный проход `i = 0..m-1` не нашёл свободного места, таблица просто удваивается ещё раз. +- **Двойное хеширование** — `idx = (base + i·step) mod m`, где `step` считается от независимого второго хешера `h2_`. Это ближе всего к равномерному хешированию из всех трёх схем. Важный нюанс для корректности: чтобы последовательность `i·step mod m` обошла все `m` остатков, шаг обязан быть взаимно прост с `m`. В коде `StepHash` берёт `step = h2(key) mod (m - 1) + 1`, то есть `step` гарантированно лежит в `[1, m-1]`, но взаимная простота с `m` явно не проверяется — при `m`, равном степени двойки (а начальная и все последующие ёмкости в `HashMap` кратны степеням двойки), чётный `step` заставит пробу двигаться только по слотам одной чётности. Это не ломает корректность (алгоритм найдёт своё же значение или свободное место, если оно есть в достижимой части, а если не найдёт — уйдёт в `Grow`), но снижает эффективное покрытие таблицы для части ключей и на практике проявляется как более частые ресайзы, чем в теоретической оценке. + +Удаление реализовано через **надгробия** (`Node::deleted = true`), а не физическое освобождение слота. Это принципиально: если при удалении просто занулить слот, следующий поиск по цепочке проб может ошибочно решить, что дальше по последовательности элементов нет, и остановиться раньше, чем найдёт искомый ключ, который на самом деле лежит дальше. Поэтому в `Search` и `Delete` цикл останавливается только на настоящем `nullptr` (слот, в который вообще никогда ничего не клали), а помеченные удалёнными узлы — пропускаются, но не прерывают проход. При вставке, наоборот, первый встреченный слот-надгробие запоминается как кандидат на переиспользование (`first_free`), но проход продолжается до конца, чтобы сначала убедиться, что ключа ещё нет дальше в таблице. + +`Grow` пересоздаёт таблицу нужного размера, пересевает оба хешера (`h1_`, `h2_`) и заново вставляет только живые (не помеченные удалёнными) узлы — надгробия, естественно, при ресайзе исчезают, так как каждый элемент вставляется в новую таблицу с нуля. + +При `α = 0.7` и равномерном хешировании классические оценки числа проб (Кормен, теорема 11.6 и далее) дают примерно так: для неуспешного поиска — `1/(1-α) ≈ 3.3` проб, для успешного — около `(1/α)·ln(1/(1-α)) ≈ 1.7` проб в среднем. Это ориентир именно для двойного хеширования; линейное и квадратичное пробирование на практике проигрывают этой оценке из-за кластеризации, описанной выше. + +### Общий интерфейс — `IBackend.hpp` + +Чисто абстрактный класс с четырьмя методами (`Insert`, `Search`, `Delete`, `Size`, `Capacity`), которые обязаны реализовать оба бэкенда. `HashMap` работает с ним только через указатель, не зная, какая именно стратегия скрыта внутри — классический пример полиморфизма через интерфейс вместо `if/switch` по всему коду. + +### Фасад — `HashMap.hpp` + +`HashMap` ничего не делает сам — это тонкая обёртка над `std::unique_ptr>`. При создании по значению `Strategy` (`Chaining`, `LinearProbing`, `QuadraticProbing`, `DoubleHashing`) статический метод `MakeBackend` собирает нужную реализацию. Дальше все вызовы — просто делегирование в `backend_`. `LoadFactor()` — единственный метод, который считается прямо здесь, как `Size() / Capacity()`. + +### Сложность операций + +| Структура | Insert (в среднем) | Search (в среднем) | Delete (в среднем) | Память | +|---|---|---|---|---| +| `DirectAddressTable` | O(1) всегда | O(1) всегда | O(1) всегда | O(\|U\|) | +| `ChainingBackend` | O(1) амортизированно | O(1 + α) | O(1 + α) | O(n + m) | +| `OpenAddressingBackend` (линейное) | O(1/(1-α)), хуже из-за кластеризации | O(1/(1-α)) | O(1/(1-α)) | O(m) | +| `OpenAddressingBackend` (квадратичное) | ближе к O(1/(1-α)) | ближе к O(1/(1-α)) | ближе к O(1/(1-α)) | O(m) | +| `OpenAddressingBackend` (двойное) | ≈ O(1/(1-α)) | ≈ O(1/(1-α)) | ≈ O(1/(1-α)) | O(m) | + +где `α` — коэффициент заполнения, `n` — число элементов, `m` — число бакетов/слотов. + +### Сборка и тестирование + +`stress_test.cpp` не полагается на ручные проверки — он сверяет каждую из четырёх стратегий с `std::unordered_map` как эталоном (`FuzzAgainstOracle`), отдельно для `int` и `string` ключей, вставляя, ища и удаляя случайные ключи в случайной пропорции. Дополнительно есть проверка роста (`GrowthStressTest` — коэффициент заполнения не должен превышать 1.0 после серии вставок, а старые ключи не должны теряться при ресайзе), замер производительности (`TimingBenchmark`) и проверка самой универсальной хеш-функции на равномерность через критерий хи-квадрат (`UniversalHashDistributionTest`) — распределение попаданий по бакетам не должно значимо отклоняться от равномерного. + +```bash +cd cmake-build-debug +cmake --build . --target stress_hash_map +./stress_hash_map [operations] [seed] +``` + +Оба аргумента опциональны: `operations` — число операций на один прогон фаззера (по умолчанию 200000), `seed` — зерно генератора случайных чисел. + +### Литература + +- Кормен Т., Лейзерсон Ч., Ривест Р., Штайн К. «Алгоритмы: построение и анализ» — главы 11 (хеш-таблицы, прямая адресация, цепочки, открытая адресация, универсальное хеширование). +- Курс «Алгоритмы и структуры данных» ФКН НИУ ВШЭ — материалы по хешированию и амортизационному анализу удвоения таблиц. + +--- + +## English + +A hash table is a structure that stores key-value pairs and, on average, gives O(1) insert, search, and delete. The price for that is collisions: with enough keys and few enough slots, two different keys almost inevitably land in the same place. The difference between hash table implementations mostly comes down to how they deal with that. + +This project has five structures sharing a common `IBackend` interface, plus a standalone `DirectAddressTable` for the case where collisions aren't a concern at all. + +### Direct addressing — `DirectAddressTable.hpp` + +The simplest case: the key universe `U` is small enough to just allocate an array of size `|U|`, where `T[k]` stores the value for key `k` directly, no hashing involved. This is classic direct addressing (Cormen, Leiserson, Rivest, Stein, chapter 11.1). + +`slots_` is a vector of `std::optional` sized `universe_size`. `Insert`, `Search`, and `Delete` are honest O(1) — a plain index access; `CheckRange` throws if the key falls outside the universe. The cost of that speed is memory: the table always occupies `O(|U|)`, even if only a handful of keys out of a million are actually used. That's the limitation baked in — this isn't a general-purpose structure, it's a tool for cases where keys are, say, small integers or indices with a known upper bound. + +### Universal hashing — `UniversalHash.hpp` + +The problem with any single fixed hash function is that there always exists some input on which it degenerates into one bucket — an adversary (or just an unlucky dataset) can know the function in advance. Universal hashing fixes this by picking the function randomly out of a family every time the table is created or resized. + +The family used here is the standard one: + +``` +h_{a,b}(x) = ((a·x + b) mod p) mod m +``` + +where `p` is a prime guaranteed larger than any possible `x` (`2^61 - 1` in the code), `a` is drawn uniformly from `{1, ..., p-1}`, `b` uniformly from `{0, ..., p-1}`, and `m` is the table size. Every call to `Reseed()` (in the constructor and in `Rehash`) redraws `a` and `b` via `std::mt19937_64`. + +The key property of this family: for any two distinct `x ≠ y`, + +``` +Pr[h(x) = h(y)] ≤ 1/m +``` + +the probability is taken over the random choice of `a` and `b`, not over the input. This is where the rest of the math comes from: no matter how many times the program runs on the same keys, there's no way to reliably force a collision, because the function is different each time. + +`KeyHasher` wraps `UniversalHash`: an arbitrary key `K` is first reduced to `uint64_t` via `std::hash`, then passed through the universal hash function. Two separate `KeyHasher` instances (as with `h1_` and `h2_` in open addressing) hash independently, each with its own random `a`, `b`. + +### Separate chaining — `ChainingBackend.hpp` + +Each bucket is a `std::list>`. On a collision, the element is simply appended to that bucket's list rather than looking for another spot. + +- `Insert`: first checks the load factor `(count_ + 1) / buckets_.size()`; if it has reached `max_load_factor_` (1.0 by default), the table doubles *before* the insertion happens. Then it does a linear scan of the target bucket, either updating an existing key or appending a new node. +- `Search` and `Delete` are a linear scan of the relevant bucket. +- `Grow`: allocates a new bucket vector, reseeds the hasher for the new size (`Rehash`), and moves every element from the old table into the new one — the bucket changes because the hash function itself changed. + +The math here is textbook (Cormen, chapter 11.2): under simple uniform hashing, with load factor `α = n/m`, the expected length of a non-empty chain is `O(1 + α)`, which is also the expected time for an unsuccessful search. Since this implementation doubles the table before `α` exceeds 1, average chain length never grows unbounded — the amortized cost of an operation stays `O(1)`, and the resize itself, while `O(n)`, happens progressively less often as the table grows (the standard amortized-doubling argument). + +### Open addressing — `OpenAddressingBackend.hpp` + +Here collisions are resolved differently: every element lives in a single array, `slots_`, and on a collision a key looks for the next free slot along a predetermined probe sequence. The maximum load factor is `0.7` (`kMaxLoadFactor`), noticeably lower than chaining — open addressing degrades sharply as `α` approaches 1, so extra headroom is needed at all times. + +The probe sequence is `⟨h(k,0), h(k,1), ..., h(k,m-1)⟩`, and ideally (under the uniform hashing assumption) it should be an equally likely permutation of all `m` indices for each key. Three strategies are implemented via `Probe(base, step, i)`: + +- **Linear probing** — `idx = (base + i) mod m`. Cheapest to compute, but prone to primary clustering: adjacent occupied slots tend to merge into long runs, because any key whose `base` falls inside such a run just extends it further. +- **Quadratic probing** — `idx = (base + i²) mod m`. No primary clustering, but secondary clustering appears instead: two keys sharing the same `base` follow the exact same probe sequence. One subtlety: quadratic probing is only guaranteed to visit all `m` slots for certain values of `m` (e.g. a prime `m` of the form `4k+3`, or specific constant choices); for arbitrary even `m`, as happens here after doubling, some slots can in theory be unreachable from a given `base` in a single pass. `InsertInto` guards against this in practice — if a full pass over `i = 0..m-1` finds no free slot, the table simply doubles again. +- **Double hashing** — `idx = (base + i·step) mod m`, with `step` computed from an independent second hasher, `h2_`. This is the closest of the three to true uniform hashing. There's an important correctness nuance here: for `i·step mod m` to cycle through all `m` residues, `step` must be coprime with `m`. `StepHash` computes `step = h2(key) mod (m - 1) + 1`, so it's guaranteed to land in `[1, m-1]`, but coprimality with `m` isn't explicitly enforced — since `m` is always a power of two in this codebase (all initial and grown capacities are), an even `step` restricts the probe to slots of a single parity. This doesn't break correctness (the algorithm still finds its own key or a free slot within whatever part of the table it can reach, and falls back to `Grow` otherwise), but it reduces effective table coverage for some keys, and in practice shows up as somewhat more frequent resizes than the theoretical bound would predict. + +Deletion is implemented via **tombstones** (`Node::deleted = true`) rather than physically clearing the slot. This matters: if a delete simply zeroed the slot, a later search walking the same probe sequence could wrongly conclude the chain ends there and stop early, missing a key that's actually stored further along. That's why `Search` and `Delete` only stop on a true `nullptr` — a slot that was never occupied at all — while tombstoned nodes are skipped but don't terminate the scan. Insertion, conversely, remembers the first tombstone it passes as a candidate for reuse (`first_free`), but keeps scanning to the end first, to make sure the key isn't already present further down the sequence. + +`Grow` rebuilds the table at the new size, reseeds both hashers (`h1_`, `h2_`), and reinserts only the live (non-deleted) nodes — tombstones naturally disappear on resize, since every surviving element is inserted into the fresh table from scratch. + +At `α = 0.7` under uniform hashing, the classical probe-count bounds (Cormen, theorem 11.6 onward) work out to roughly: `1/(1-α) ≈ 3.3` probes for an unsuccessful search, and about `(1/α)·ln(1/(1-α)) ≈ 1.7` probes for a successful one. That's the reference figure specifically for double hashing; linear and quadratic probing underperform this bound in practice because of the clustering described above. + +### The common interface — `IBackend.hpp` + +A pure abstract class with four operations (`Insert`, `Search`, `Delete`, `Size`, `Capacity`) that both backends must implement. `HashMap` only ever talks to it through a pointer, with no idea which strategy is hiding underneath — a straightforward case of polymorphism replacing an `if`/`switch` scattered through the codebase. + +### The facade — `HashMap.hpp` + +`HashMap` doesn't do any work itself — it's a thin wrapper around a `std::unique_ptr>`. Given a `Strategy` value (`Chaining`, `LinearProbing`, `QuadraticProbing`, `DoubleHashing`), the static `MakeBackend` method assembles the right implementation. Every other call just delegates to `backend_`. `LoadFactor()` is the one method actually computed here, as `Size() / Capacity()`. + +### Operation complexity + +| Structure | Insert (avg) | Search (avg) | Delete (avg) | Memory | +|---|---|---|---|---| +| `DirectAddressTable` | O(1) always | O(1) always | O(1) always | O(\|U\|) | +| `ChainingBackend` | O(1) amortized | O(1 + α) | O(1 + α) | O(n + m) | +| `OpenAddressingBackend` (linear) | O(1/(1-α)), worse due to clustering | O(1/(1-α)) | O(1/(1-α)) | O(m) | +| `OpenAddressingBackend` (quadratic) | closer to O(1/(1-α)) | closer to O(1/(1-α)) | closer to O(1/(1-α)) | O(m) | +| `OpenAddressingBackend` (double) | ≈ O(1/(1-α)) | ≈ O(1/(1-α)) | ≈ O(1/(1-α)) | O(m) | + +where `α` is the load factor, `n` the number of stored elements, `m` the number of buckets/slots. + +### Build and test + +`stress_test.cpp` doesn't rely on manual assertions — it checks all four strategies against `std::unordered_map` as an oracle (`FuzzAgainstOracle`), separately for `int` and `string` keys, mixing random inserts, searches, and deletes. There's also a growth check (`GrowthStressTest` — load factor must never exceed 1.0 after a run of inserts, and old keys must survive resizing), a timing benchmark (`TimingBenchmark`), and a uniformity check on the universal hash function itself using a chi-squared test (`UniversalHashDistributionTest`) — the distribution of hits across buckets shouldn't deviate significantly from uniform. + +```bash +cd cmake-build-debug +cmake --build . --target stress_hash_map +./stress_hash_map [operations] [seed] +``` + +Both arguments are optional: `operations` is the number of ops per fuzzing run (default 200000), `seed` is the random number generator seed. + +### References + +- Cormen T., Leiserson C., Rivest R., Stein C. *Introduction to Algorithms* — chapter 11 (hash tables, direct addressing, chaining, open addressing, universal hashing). +- HSE FCS "Algorithms and Data Structures" course materials — hashing and amortized analysis of table doubling. + +--- + +
+ +> Хеш-таблица не хранит порядок — она хранит только адрес. Ключ приходит, функция считает число, и элемент оказывается там, где случайность решила его положить, а не там, где ему было бы «правильно» лежать по смыслу. Коллизия — это не ошибка устройства, а его нормальное состояние: два разных пути почти всегда рано или поздно приводят в одну и ту же дверь. Вопрос только в том, что происходит дальше — уступают ли место соседям в очереди или ищут себе следующую свободную дверь сами. +> +> *A hash table doesn't keep order — it only keeps an address. A key comes in, the function computes a number, and the element ends up wherever chance decided to put it, not wherever it would "belong" by meaning. A collision isn't a flaw in the design, it's its normal state: two different paths almost always end up at the same door sooner or later. The only question is what happens next — whether they make room in a line at that door, or go looking for the next free one themselves.* \ No newline at end of file diff --git a/hash_map/stress_test.cpp b/hash_map/stress_test.cpp new file mode 100644 index 0000000..de8b9b9 --- /dev/null +++ b/hash_map/stress_test.cpp @@ -0,0 +1,309 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "DirectAddressTable.hpp" +#include "HashMap.hpp" +#include "UniversalHash.hpp" + +using namespace hashmap; +using Clock = std::chrono::steady_clock; + +namespace { + +int g_failures = 0; + +void Check(bool condition, const std::string& message) { + if (!condition) { + std::cerr << " [FAIL] " << message << "\n"; + ++g_failures; + } +} + +std::string RandomString(std::mt19937_64& rng, size_t max_len = 12) { + static const char kAlphabet[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + std::uniform_int_distribution len_dist(1, max_len); + std::uniform_int_distribution ch_dist(0, sizeof(kAlphabet) - 2); + size_t len = len_dist(rng); + std::string s; + s.reserve(len); + for (size_t i = 0; i < len; ++i) { + s.push_back(kAlphabet[ch_dist(rng)]); + } + return s; +} + +std::string DebugKey(int k); +std::string DebugKey(const std::string& k); + +const char* StrategyName(Strategy s) { + switch (s) { + case Strategy::Chaining: return "Chaining"; + case Strategy::LinearProbing: return "LinearProbing"; + case Strategy::QuadraticProbing: return "QuadraticProbing"; + case Strategy::DoubleHashing: return "DoubleHashing"; + } + return "?"; +} + +template +void FuzzAgainstOracle(Strategy strategy, size_t operations, size_t key_space, + std::mt19937_64& rng, const std::function& gen_key) { + HashMap map(strategy, 8); + std::unordered_map oracle; + + std::uniform_int_distribution op_dist(0, 99); + std::uniform_int_distribution value_dist(-1000000, 1000000); + std::vector known_keys; + known_keys.reserve(key_space); + + for (size_t op = 0; op < operations; ++op) { + int roll = op_dist(rng); + K key = gen_key(rng); + + if (roll < 55) { + // Insert (55%) + int value = value_dist(rng); + map.Insert(key, value); + oracle[key] = value; + } else if (roll < 85) { + // Search (30%) + auto got = map.Search(key); + auto it = oracle.find(key); + if (it == oracle.end()) { + Check(!got.has_value(), "Search should miss for a key never inserted: " + DebugKey(key)); + } else { + Check(got.has_value() && got.value() == it->second, + "Search value mismatch for key " + DebugKey(key)); + } + } else { + // Delete (15%) + bool deleted = map.Delete(key); + bool existed = oracle.erase(key) > 0; + Check(deleted == existed, "Delete result mismatch for key " + DebugKey(key)); + } + + if (op % 4000 == 3999) { + Check(map.Size() == oracle.size(), "Size mismatch mid-run"); + } + } + + Check(map.Size() == oracle.size(), "Final size mismatch"); + for (const auto& [k, v] : oracle) { + auto got = map.Search(k); + Check(got.has_value() && got.value() == v, "Final content mismatch for key " + DebugKey(k)); + } + + std::cout << " [" << StrategyName(strategy) << "] fuzz OK: " << operations + << " ops, final size=" << map.Size() << ", capacity=" << map.Capacity() + << ", load_factor=" << std::fixed << std::setprecision(3) << map.LoadFactor() << "\n"; +} + +std::string DebugKey(int k) { return std::to_string(k); } +std::string DebugKey(const std::string& k) { return "\"" + k + "\""; } + +void GrowthStressTest(Strategy strategy, size_t n) { + HashMap map(strategy, 4); + for (int i = 0; i < static_cast(n); ++i) { + map.Insert(i, i * 31 + 7); + } + Check(map.Size() == n, "Growth: final size mismatch"); + Check(map.LoadFactor() <= 1.0, "Growth: load factor exceeded 1.0"); + + std::mt19937_64 rng(123); + std::uniform_int_distribution idx_dist(0, static_cast(n) - 1); + for (int i = 0; i < 2000; ++i) { + int k = idx_dist(rng); + auto v = map.Search(k); + Check(v.has_value() && v.value() == k * 31 + 7, "Growth: lost key " + std::to_string(k) + " after rehash"); + } + + std::cout << " [" << StrategyName(strategy) << "] growth OK: n=" << n + << ", capacity=" << map.Capacity() << ", load_factor=" << std::fixed + << std::setprecision(3) << map.LoadFactor() << "\n"; +} + +void TimingBenchmark(Strategy strategy, size_t n) { + std::mt19937_64 rng(777); + std::vector keys(n); + for (size_t i = 0; i < n; ++i) keys[i] = static_cast(i); + std::shuffle(keys.begin(), keys.end(), rng); + + HashMap map(strategy, 16); + + auto t0 = Clock::now(); + for (int k : keys) { + map.Insert(k, k); + } + auto t1 = Clock::now(); + + std::shuffle(keys.begin(), keys.end(), rng); + volatile long sink = 0; + for (int k : keys) { + sink += map.Search(k).value_or(-1); + } + auto t2 = Clock::now(); + + std::shuffle(keys.begin(), keys.end(), rng); + for (int k : keys) { + std::ignore = map.Delete(k); + } + auto t3 = Clock::now(); + + auto ms = [](Clock::time_point a, Clock::time_point b) { + return std::chrono::duration(b - a).count(); + }; + double insert_ms = ms(t0, t1), search_ms = ms(t1, t2), delete_ms = ms(t2, t3); + + std::cout << " [" << std::left << std::setw(18) << StrategyName(strategy) << "] n=" << n + << std::right << " insert=" << std::setw(8) << std::fixed << std::setprecision(1) << insert_ms + << " ms (" << std::setw(8) << static_cast(n / (insert_ms / 1000.0)) << " ops/s)" + << " search=" << std::setw(8) << search_ms << " ms (" << std::setw(8) + << static_cast(n / (search_ms / 1000.0)) << " ops/s)" + << " delete=" << std::setw(8) << delete_ms << " ms (" << std::setw(8) + << static_cast(n / (delete_ms / 1000.0)) << " ops/s)\n"; + + (void)sink; +} + +void DirectAddressStressTest(size_t universe, size_t operations, std::mt19937_64& rng) { + DirectAddressTable table(universe); + std::vector> oracle(universe); + + std::uniform_int_distribution key_dist(0, universe - 1); + std::uniform_int_distribution op_dist(0, 99); + std::uniform_int_distribution value_dist(-1000, 1000); + + for (size_t op = 0; op < operations; ++op) { + size_t key = key_dist(rng); + int roll = op_dist(rng); + + if (roll < 60) { + int value = value_dist(rng); + table.Insert(key, value); + oracle[key] = value; + } else if (roll < 85) { + auto got = table.Search(key); + Check(got == oracle[key], "DirectAddress: search mismatch at key " + std::to_string(key)); + } else { + bool deleted = table.Delete(key); + bool existed = oracle[key].has_value(); + Check(deleted == existed, "DirectAddress: delete result mismatch at key " + std::to_string(key)); + oracle[key].reset(); + } + } + + size_t expected_size = 0; + for (const auto& v : oracle) { + if (v.has_value()) { + ++expected_size; + } + } + Check(table.Size() == expected_size, "DirectAddress: final size mismatch"); + + std::cout << " DirectAddressTable fuzz OK: " << operations << " ops over universe=" << universe + << ", final size=" << table.Size() << "\n"; +} + +void UniversalHashDistributionTest(uint64_t m, uint64_t n, std::mt19937_64& rng) { + UniversalHash h(m); + std::vector buckets(m, 0); + std::uniform_int_distribution x_dist; + + for (uint64_t i = 0; i < n; ++i) { + uint64_t idx = h(x_dist(rng)); + ++buckets[idx]; + } + + double expected = static_cast(n) / static_cast(m); + double chi_sq = 0.0; + uint64_t max_bucket = 0; + for (uint64_t count : buckets) { + double diff = static_cast(count) - expected; + chi_sq += diff * diff / expected; + max_bucket = std::max(max_bucket, count); + } + + double threshold = m + 8.0 * std::sqrt(2.0 * m); + Check(chi_sq < threshold * 3.0, "UniversalHash: chi-squared too high, distribution looks skewed"); + + std::cout << " UniversalHash distribution OK: m=" << m << " n=" << n << " chi_sq=" << std::fixed + << std::setprecision(1) << chi_sq << " (threshold~" << threshold << "), max_bucket=" << max_bucket + << " (expected~" << static_cast(expected) << ")\n"; +} + +} + +int main(int argc, char** argv) { + size_t operations = 200000; + uint64_t seed = 42; + if (argc > 1) { + operations = static_cast(std::strtoull(argv[1], nullptr, 10)); + } + if (argc > 2) { + seed = std::strtoull(argv[2], nullptr, 10); + } + + std::mt19937_64 rng(seed); + std::cout << "Stress test: operations=" << operations << " seed=" << seed << "\n\n"; + + const Strategy strategies[] = {Strategy::Chaining, Strategy::LinearProbing, Strategy::QuadraticProbing, + Strategy::DoubleHashing}; + + std::cout << "== 1) Correctness fuzzing vs std::unordered_map (int keys) ==\n"; + for (Strategy s : strategies) { + std::mt19937_64 local_rng(seed + static_cast(s) * 1000 + 1); + std::function gen_key = [](std::mt19937_64& r) { + std::uniform_int_distribution d(0, 5000); + return d(r); + }; + FuzzAgainstOracle(s, operations, 5000, local_rng, gen_key); + } + + std::cout << "\n== 1b) Correctness fuzzing vs std::unordered_map (string keys) ==\n"; + for (Strategy s : strategies) { + std::mt19937_64 local_rng(seed + static_cast(s) * 1000 + 2); + std::function gen_key = [](std::mt19937_64& r) { + return RandomString(r, 6); + }; + FuzzAgainstOracle(s, operations, 5000, local_rng, gen_key); + } + + std::cout << "\n== 2) Growth stress (monotonic insert, checking load factor & survival) ==\n"; + for (Strategy s : strategies) { + GrowthStressTest(s, std::max(operations, 50000)); + } + + std::cout << "\n== 3) Timing benchmark ==\n"; + for (size_t n : {10000ul, 100000ul, 1000000ul}) { + for (Strategy s : strategies) { + TimingBenchmark(s, n); + } + std::cout << "\n"; + } + + std::cout << "== 4) DirectAddressTable fuzzing ==\n"; + DirectAddressStressTest(/*universe=*/10000, operations, rng); + + std::cout << "\n== 5) UniversalHash distribution check ==\n"; + UniversalHashDistributionTest(/*m=*/1024, /*n=*/2000000, rng); + UniversalHashDistributionTest(/*m=*/37, /*n=*/500000, rng); + + std::cout << "\n"; + if (g_failures == 0) { + std::cout << "ALL STRESS TESTS PASSED.\n"; + return 0; + } + std::cerr << g_failures << " CHECK(S) FAILED.\n"; + return 1; +}