Add Graph, Trie, LRU modules

Void::Graph — DiGraph<V,E> directed adjacency-list graph: add_vertex/add_edge,
has_vertex/has_edge, BFS/DFS traversal, topological sort (Kahn, returns nullopt
on cycle), can_reach, shortest_path (BFS, unweighted).

Void::Trie — Prefix tree Trie<V>: insert, contains, get, starts_with, erase
(with node pruning), keys_with_prefix, size/empty.

Void::LRU — LruCache<K,V>: get (promotes to MRU), put (evicts LRU when full),
peek (no promotion), erase, clear, contains, full/empty/size.

42/42 tests pass.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 4.6 committed 2026-05-14 22:57:53 +03:00
1 parent 388e75011f
commit 3c3ff46e39
6 files changed
+866

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
#pragma once
#include <algorithm>
#include <cstddef>
#include <functional>
#include <optional>
#include <queue>
#include <ranges>
#include <span>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace Void::Graph
{
// ── DiGraph<V, E> ─────────────────────────────────────────────────────────────
// Directed graph with vertex labels of type V and edge weights of type E.
// Vertices are identified by a user-supplied key of type V (must be hashable).
template <typename V, typename E = int>
class DiGraph
{
public:
struct Edge
{
V to;
E weight;
};
void add_vertex(const V& v) { adj_[v]; }
void add_edge(const V& from, const V& to, E weight = E{})
{
adj_[from].push_back({to, weight});
adj_.try_emplace(to);
}
[[nodiscard]] bool has_vertex(const V& v) const
{
return adj_.contains(v);
}
[[nodiscard]] bool has_edge(const V& from, const V& to) const
{
auto it = adj_.find(from);
if (it == adj_.end()) return false;
return std::ranges::any_of(it->second,
[&](const Edge& e) { return e.to == to; });
}
[[nodiscard]] const std::vector<Edge>& neighbors(const V& v) const
{
return adj_.at(v);
}
[[nodiscard]] std::size_t vertex_count() const noexcept
{
return adj_.size();
}
[[nodiscard]] std::size_t edge_count() const noexcept
{
std::size_t n = 0;
for (const auto& [_, edges] : adj_) n += edges.size();
return n;
}
// ── BFS ──────────────────────────────────────────────────────────────────
void bfs(const V& start,
std::function<void(const V&)> visit) const
{
if (!adj_.contains(start)) return;
std::unordered_set<V> visited;
std::queue<V> q;
visited.insert(start);
q.push(start);
while (!q.empty()) {
const V cur = q.front(); q.pop();
visit(cur);
for (const auto& e : adj_.at(cur)) {
if (!visited.contains(e.to)) {
visited.insert(e.to);
q.push(e.to);
}
}
}
}
[[nodiscard]] std::vector<V> bfs_order(const V& start) const
{
std::vector<V> result;
bfs(start, [&](const V& v) { result.push_back(v); });
return result;
}
// ── DFS ──────────────────────────────────────────────────────────────────
void dfs(const V& start,
std::function<void(const V&)> visit) const
{
std::unordered_set<V> visited;
dfs_impl(start, visited, visit);
}
[[nodiscard]] std::vector<V> dfs_order(const V& start) const
{
std::vector<V> result;
dfs(start, [&](const V& v) { result.push_back(v); });
return result;
}
// ── Topological sort (Kahn's algorithm) ──────────────────────────────────
// Returns nullopt if the graph has a cycle.
[[nodiscard]] std::optional<std::vector<V>> topological_sort() const
{
std::unordered_map<V, int> in_degree;
for (const auto& [v, _] : adj_) in_degree[v] = 0;
for (const auto& [v, edges] : adj_) {
for (const auto& e : edges) in_degree[e.to]++;
}
std::queue<V> q;
for (const auto& [v, deg] : in_degree) {
if (deg == 0) q.push(v);
}
std::vector<V> order;
while (!q.empty()) {
V cur = q.front(); q.pop();
order.push_back(cur);
for (const auto& e : adj_.at(cur)) {
if (--in_degree[e.to] == 0) q.push(e.to);
}
}
if (order.size() != adj_.size()) return std::nullopt; // cycle
return order;
}
// ── Reachability ─────────────────────────────────────────────────────────
[[nodiscard]] bool can_reach(const V& from, const V& to) const
{
bool found = false;
bfs(from, [&](const V& v) { if (v == to) found = true; });
return found;
}
// ── Shortest path (BFS, unweighted) ──────────────────────────────────────
[[nodiscard]] std::optional<std::vector<V>>
shortest_path(const V& from, const V& to) const
{
if (!adj_.contains(from) || !adj_.contains(to)) return std::nullopt;
std::unordered_map<V, V> parent;
std::unordered_set<V> visited;
std::queue<V> q;
visited.insert(from);
q.push(from);
bool found = false;
while (!q.empty() && !found) {
V cur = q.front(); q.pop();
for (const auto& e : adj_.at(cur)) {
if (!visited.contains(e.to)) {
visited.insert(e.to);
parent[e.to] = cur;
if (e.to == to) { found = true; break; }
q.push(e.to);
}
}
}
if (!found && from != to) return std::nullopt;
std::vector<V> path;
V cur = to;
while (cur != from) {
path.push_back(cur);
cur = parent.at(cur);
}
path.push_back(from);
std::ranges::reverse(path);
return path;
}
private:
void dfs_impl(const V& v, std::unordered_set<V>& visited,
std::function<void(const V&)>& visit) const
{
if (visited.contains(v)) return;
visited.insert(v);
visit(v);
if (adj_.contains(v)) {
for (const auto& e : adj_.at(v)) {
dfs_impl(e.to, visited, visit);
}
}
}
std::unordered_map<V, std::vector<Edge>> adj_;
};
} // namespace Void::Graph
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <cstddef>
#include <list>
#include <optional>
#include <stdexcept>
#include <unordered_map>
#include <utility>
namespace Void::LRU
{
// ── LruCache<K, V> ────────────────────────────────────────────────────────────
// Fixed-capacity LRU cache. get() promotes to MRU; put() evicts LRU when full.
// All operations are O(1) amortized via a doubly-linked list + hash map.
template <typename K, typename V>
class LruCache
{
using List = std::list<std::pair<K, V>>;
using Map = std::unordered_map<K, typename List::iterator>;
public:
explicit LruCache(std::size_t capacity)
: capacity_{capacity}
{
if (capacity == 0) throw std::invalid_argument{"capacity must be > 0"};
}
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
[[nodiscard]] std::size_t size() const noexcept { return map_.size(); }
[[nodiscard]] bool empty() const noexcept { return map_.empty(); }
[[nodiscard]] bool full() const noexcept { return map_.size() == capacity_; }
// Retrieve a value. Returns nullopt on miss; promotes the entry on hit.
[[nodiscard]] std::optional<V> get(const K& key)
{
auto it = map_.find(key);
if (it == map_.end()) return std::nullopt;
list_.splice(list_.begin(), list_, it->second);
return it->second->second;
}
// Peek without changing recency order.
[[nodiscard]] const V* peek(const K& key) const
{
auto it = map_.find(key);
if (it == map_.end()) return nullptr;
return &it->second->second;
}
// Insert or update. If the key already exists its recency is updated.
// If the cache is full the least-recently-used entry is evicted.
void put(const K& key, V value)
{
auto it = map_.find(key);
if (it != map_.end()) {
it->second->second = std::move(value);
list_.splice(list_.begin(), list_, it->second);
return;
}
if (map_.size() == capacity_) {
map_.erase(list_.back().first);
list_.pop_back();
}
list_.emplace_front(key, std::move(value));
map_[key] = list_.begin();
}
bool erase(const K& key)
{
auto it = map_.find(key);
if (it == map_.end()) return false;
list_.erase(it->second);
map_.erase(it);
return true;
}
void clear() noexcept
{
list_.clear();
map_.clear();
}
[[nodiscard]] bool contains(const K& key) const
{
return map_.contains(key);
}
// Iterate entries in MRU→LRU order (const).
[[nodiscard]] const List& entries() const noexcept { return list_; }
private:
std::size_t capacity_;
List list_;
Map map_;
};
} // namespace Void::LRU
+124
View File
@@ -0,0 +1,124 @@
#pragma once
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
namespace Void::Trie
{
// ── Trie ──────────────────────────────────────────────────────────────────────
// Prefix tree over std::string keys with optional associated values of type V.
// Stores words character-by-character; each node has up to 256 children.
template <typename V = bool>
class Trie
{
struct Node
{
std::unordered_map<char, std::unique_ptr<Node>> children;
std::optional<V> value; // set only at end-of-word nodes
};
public:
Trie() : root_{std::make_unique<Node>()} {}
void insert(std::string_view key, V value = V{})
{
Node* cur = root_.get();
for (char c : key) {
auto& child = cur->children[c];
if (!child) child = std::make_unique<Node>();
cur = child.get();
}
if (!cur->value.has_value()) ++size_;
cur->value = std::move(value);
}
[[nodiscard]] bool contains(std::string_view key) const
{
const Node* node = find_node(key);
return node && node->value.has_value();
}
[[nodiscard]] std::optional<V> get(std::string_view key) const
{
const Node* node = find_node(key);
if (!node) return std::nullopt;
return node->value;
}
bool erase(std::string_view key)
{
return erase_impl(root_.get(), key, 0);
}
[[nodiscard]] bool starts_with(std::string_view prefix) const
{
return find_node(prefix) != nullptr;
}
[[nodiscard]] std::vector<std::string>
keys_with_prefix(std::string_view prefix) const
{
std::vector<std::string> result;
const Node* node = find_node(prefix);
if (!node) return result;
std::string buf{prefix};
collect(node, buf, result);
return result;
}
[[nodiscard]] std::size_t size() const noexcept { return size_; }
[[nodiscard]] bool empty() const noexcept { return size_ == 0; }
private:
const Node* find_node(std::string_view key) const
{
const Node* cur = root_.get();
for (char c : key) {
auto it = cur->children.find(c);
if (it == cur->children.end()) return nullptr;
cur = it->second.get();
}
return cur;
}
void collect(const Node* node, std::string& buf,
std::vector<std::string>& out) const
{
if (node->value.has_value()) out.push_back(buf);
for (const auto& [c, child] : node->children) {
buf += c;
collect(child.get(), buf, out);
buf.pop_back();
}
}
bool erase_impl(Node* node, std::string_view key, std::size_t depth)
{
if (depth == key.size()) {
if (!node->value.has_value()) return false;
node->value.reset();
--size_;
return true;
}
auto it = node->children.find(key[depth]);
if (it == node->children.end()) return false;
const bool erased = erase_impl(it->second.get(), key, depth + 1);
// Prune leaf nodes that hold no value and have no children
if (erased && it->second->children.empty() &&
!it->second->value.has_value()) {
node->children.erase(it);
}
return erased;
}
std::unique_ptr<Node> root_;
std::size_t size_{0};
};
} // namespace Void::Trie
+159
View File
@@ -0,0 +1,159 @@
#include <Void/Graph/Graph.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <vector>
using G = Void::Graph::DiGraph<int>;
// ── Vertices ──────────────────────────────────────────────────────────────────
Void::Testing::Test graph_add_vertex()
{
G g;
g.add_vertex(1);
Void::Testing::expect(g.has_vertex(1));
Void::Testing::expect_eq(g.vertex_count(), std::size_t{1});
}
Void::Testing::Test graph_add_edge_creates_vertices()
{
G g;
g.add_edge(1, 2);
Void::Testing::expect(g.has_vertex(1));
Void::Testing::expect(g.has_vertex(2));
}
Void::Testing::Test graph_has_edge()
{
G g;
g.add_edge(1, 2);
Void::Testing::expect(g.has_edge(1, 2));
Void::Testing::expect(!g.has_edge(2, 1));
}
Void::Testing::Test graph_edge_count()
{
G g;
g.add_edge(1, 2);
g.add_edge(2, 3);
Void::Testing::expect_eq(g.edge_count(), std::size_t{2});
}
// ── BFS ───────────────────────────────────────────────────────────────────────
Void::Testing::Test bfs_visits_all_reachable()
{
G g;
g.add_edge(1, 2);
g.add_edge(1, 3);
g.add_edge(2, 4);
auto order = g.bfs_order(1);
Void::Testing::expect_eq(order.size(), std::size_t{4});
Void::Testing::expect_eq(order[0], 1);
}
Void::Testing::Test bfs_unreachable_vertex_not_visited()
{
G g;
g.add_edge(1, 2);
g.add_vertex(5);
auto order = g.bfs_order(1);
Void::Testing::expect_eq(order.size(), std::size_t{2});
}
// ── DFS ───────────────────────────────────────────────────────────────────────
Void::Testing::Test dfs_visits_all_reachable()
{
G g;
g.add_edge(1, 2);
g.add_edge(2, 3);
auto order = g.dfs_order(1);
Void::Testing::expect_eq(order.size(), std::size_t{3});
Void::Testing::expect_eq(order[0], 1);
}
// ── Topological sort ──────────────────────────────────────────────────────────
Void::Testing::Test topo_sort_dag()
{
G g;
g.add_edge(1, 2);
g.add_edge(1, 3);
g.add_edge(2, 4);
g.add_edge(3, 4);
const auto order = g.topological_sort();
Void::Testing::expect(order.has_value());
Void::Testing::expect_eq(order->size(), std::size_t{4});
// 1 must come before 2, 3; 2 and 3 before 4
Void::Testing::expect_eq(order->front(), 1);
Void::Testing::expect_eq(order->back(), 4);
}
Void::Testing::Test topo_sort_cycle_returns_nullopt()
{
G g;
g.add_edge(1, 2);
g.add_edge(2, 3);
g.add_edge(3, 1); // cycle
Void::Testing::expect(!g.topological_sort().has_value());
}
// ── Reachability ─────────────────────────────────────────────────────────────
Void::Testing::Test can_reach_direct()
{
G g;
g.add_edge(1, 2);
Void::Testing::expect(g.can_reach(1, 2));
}
Void::Testing::Test can_reach_indirect()
{
G g;
g.add_edge(1, 2);
g.add_edge(2, 3);
Void::Testing::expect(g.can_reach(1, 3));
}
Void::Testing::Test cannot_reach_reverse()
{
G g;
g.add_edge(1, 2);
Void::Testing::expect(!g.can_reach(2, 1));
}
// ── Shortest path ─────────────────────────────────────────────────────────────
Void::Testing::Test shortest_path_direct()
{
G g;
g.add_edge(1, 2);
const auto p = g.shortest_path(1, 2);
Void::Testing::expect(p.has_value());
Void::Testing::expect_eq(p->size(), std::size_t{2});
Void::Testing::expect_eq((*p)[0], 1);
Void::Testing::expect_eq((*p)[1], 2);
}
Void::Testing::Test shortest_path_longer()
{
G g;
g.add_edge(1, 2);
g.add_edge(2, 3);
g.add_edge(1, 3); // shortcut
const auto p = g.shortest_path(1, 3);
Void::Testing::expect(p.has_value());
// BFS finds shortest (length 2: 1→3)
Void::Testing::expect_eq(p->size(), std::size_t{2});
}
Void::Testing::Test shortest_path_no_path()
{
G g;
g.add_vertex(1);
g.add_vertex(2);
Void::Testing::expect(!g.shortest_path(1, 2).has_value());
}
+133
View File
@@ -0,0 +1,133 @@
#include <Void/LRU/LRU.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <stdexcept>
#include <string>
using Cache = Void::LRU::LruCache<int, std::string>;
// ── Basic ─────────────────────────────────────────────────────────────────────
Void::Testing::Test lru_zero_capacity_throws()
{
bool threw = false;
try { Void::LRU::LruCache<int,int>{0}; }
catch (const std::invalid_argument&) { threw = true; }
Void::Testing::expect(threw);
}
Void::Testing::Test lru_put_and_get()
{
Cache c{4};
c.put(1, "one");
const auto v = c.get(1);
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(*v, std::string{"one"});
}
Void::Testing::Test lru_get_miss_returns_nullopt()
{
Cache c{4};
Void::Testing::expect(!c.get(99).has_value());
}
Void::Testing::Test lru_contains()
{
Cache c{4};
c.put(1, "a");
Void::Testing::expect(c.contains(1));
Void::Testing::expect(!c.contains(2));
}
Void::Testing::Test lru_size_and_empty()
{
Cache c{4};
Void::Testing::expect(c.empty());
c.put(1, "a");
Void::Testing::expect_eq(c.size(), std::size_t{1});
}
// ── Eviction ─────────────────────────────────────────────────────────────────
Void::Testing::Test lru_evicts_lru_when_full()
{
Cache c{3};
c.put(1, "a");
c.put(2, "b");
c.put(3, "c");
c.put(4, "d"); // evicts 1 (LRU)
Void::Testing::expect(!c.contains(1));
Void::Testing::expect(c.contains(4));
}
Void::Testing::Test lru_get_promotes_entry()
{
Cache c{3};
c.put(1, "a");
c.put(2, "b");
c.put(3, "c");
c.get(1); // promote 1 to MRU
c.put(4, "d"); // evicts 2 (now LRU)
Void::Testing::expect(c.contains(1));
Void::Testing::expect(!c.contains(2));
}
Void::Testing::Test lru_update_existing_key()
{
Cache c{4};
c.put(1, "old");
c.put(1, "new");
Void::Testing::expect_eq(c.size(), std::size_t{1});
Void::Testing::expect_eq(*c.get(1), std::string{"new"});
}
// ── Erase ────────────────────────────────────────────────────────────────────
Void::Testing::Test lru_erase_existing()
{
Cache c{4};
c.put(1, "a");
Void::Testing::expect(c.erase(1));
Void::Testing::expect(!c.contains(1));
}
Void::Testing::Test lru_erase_missing_returns_false()
{
Cache c{4};
Void::Testing::expect(!c.erase(99));
}
// ── Peek ─────────────────────────────────────────────────────────────────────
Void::Testing::Test lru_peek_does_not_promote()
{
Cache c{3};
c.put(1, "a");
c.put(2, "b");
c.put(3, "c");
c.peek(1); // peek 1 but do NOT promote
c.put(4, "d"); // evicts 1 (still LRU despite peek)
Void::Testing::expect(!c.contains(1));
}
// ── Clear ────────────────────────────────────────────────────────────────────
Void::Testing::Test lru_clear()
{
Cache c{4};
c.put(1, "a");
c.put(2, "b");
c.clear();
Void::Testing::expect(c.empty());
Void::Testing::expect(!c.contains(1));
}
Void::Testing::Test lru_full_flag()
{
Cache c{2};
c.put(1, "a");
Void::Testing::expect(!c.full());
c.put(2, "b");
Void::Testing::expect(c.full());
}
+146
View File
@@ -0,0 +1,146 @@
#include <Void/Trie/Trie.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <string>
#include <vector>
using BoolTrie = Void::Trie::Trie<bool>;
using IntTrie = Void::Trie::Trie<int>;
// ── insert / contains ─────────────────────────────────────────────────────────
Void::Testing::Test trie_insert_and_contains()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(t.contains("hello"));
}
Void::Testing::Test trie_does_not_contain_prefix_only()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(!t.contains("hell"));
}
Void::Testing::Test trie_does_not_contain_extension()
{
BoolTrie t;
t.insert("hell");
Void::Testing::expect(!t.contains("hello"));
}
Void::Testing::Test trie_insert_empty_key()
{
BoolTrie t;
t.insert("");
Void::Testing::expect(t.contains(""));
}
Void::Testing::Test trie_multiple_words()
{
BoolTrie t;
t.insert("car");
t.insert("card");
t.insert("care");
Void::Testing::expect(t.contains("car"));
Void::Testing::expect(t.contains("card"));
Void::Testing::expect(t.contains("care"));
Void::Testing::expect(!t.contains("ca"));
}
// ── get ───────────────────────────────────────────────────────────────────────
Void::Testing::Test trie_get_value()
{
IntTrie t;
t.insert("key", 42);
const auto v = t.get("key");
Void::Testing::expect(v.has_value());
Void::Testing::expect_eq(*v, 42);
}
Void::Testing::Test trie_get_missing_returns_nullopt()
{
IntTrie t;
Void::Testing::expect(!t.get("nope").has_value());
}
// ── starts_with ───────────────────────────────────────────────────────────────
Void::Testing::Test trie_starts_with_true()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(t.starts_with("hel"));
}
Void::Testing::Test trie_starts_with_false()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(!t.starts_with("world"));
}
// ── erase ────────────────────────────────────────────────────────────────────
Void::Testing::Test trie_erase_removes_word()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(t.erase("hello"));
Void::Testing::expect(!t.contains("hello"));
}
Void::Testing::Test trie_erase_prefix_word_keeps_extension()
{
BoolTrie t;
t.insert("car");
t.insert("card");
t.erase("car");
Void::Testing::expect(!t.contains("car"));
Void::Testing::expect(t.contains("card"));
}
Void::Testing::Test trie_erase_missing_returns_false()
{
BoolTrie t;
Void::Testing::expect(!t.erase("nope"));
}
// ── keys_with_prefix ──────────────────────────────────────────────────────────
Void::Testing::Test trie_keys_with_prefix()
{
BoolTrie t;
t.insert("car");
t.insert("card");
t.insert("care");
t.insert("dog");
auto keys = t.keys_with_prefix("car");
std::sort(keys.begin(), keys.end());
Void::Testing::expect_eq(keys.size(), std::size_t{3});
Void::Testing::expect_eq(keys[0], std::string{"car"});
Void::Testing::expect_eq(keys[1], std::string{"card"});
Void::Testing::expect_eq(keys[2], std::string{"care"});
}
Void::Testing::Test trie_keys_with_prefix_no_match()
{
BoolTrie t;
t.insert("hello");
Void::Testing::expect(t.keys_with_prefix("xyz").empty());
}
// ── size ─────────────────────────────────────────────────────────────────────
Void::Testing::Test trie_size_tracks_inserts()
{
BoolTrie t;
Void::Testing::expect_eq(t.size(), std::size_t{0});
t.insert("a");
t.insert("b");
Void::Testing::expect_eq(t.size(), std::size_t{2});
}