aboutsummaryrefslogtreecommitdiff
path: root/trie.cc
blob: 15a74c90c735b59b3e98a6265117fc44b5c1004c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <cstdint>
#include <forward_list>
#include <map>
#include <memory>

#include <cassert>
#include <iostream>

template <
	typename Key
>
class Trie {
	public:
		typedef std::unique_ptr<Trie> ptr;

		Trie():
			children_() { }

		inline void add(std::forward_list<Key> path) {
			this->add(path, path.begin());
		}

		inline void add(std::forward_list<Key>& path,
		                typename std::forward_list<Key>::const_iterator curr) {
			if ( curr != path.end() ) {
				Trie::ptr& trie = this->children_[*curr];

				if ( trie ) {
					trie->add(path, ++curr);
				} else {
					trie.reset(new Trie<Key>());
					trie->add(path, ++curr);
				}
			}
		}

		inline Trie* resolve(std::forward_list<Key> path) const {
			return this->resolve(path, path.begin());
		}

		inline Trie* resolve(
			std::forward_list<Key>& path,
			typename std::forward_list<Key>::const_iterator curr
		) const {
			auto trie = this->children_.find(*curr);

			if ( trie != this->children_.end() ) {
				auto next = ++curr;

				if ( next == path.end() ) {
					return (*trie).second.get();
				} else {
					return (*trie).second->resolve(path, next);
				}
			} else {
				return nullptr;
			}
		}

	protected:
		std::map<Key, Trie::ptr> children_;

};

int main() {
	Trie<uint8_t> test;

	test.add(std::forward_list<uint8_t>{1, 2, 3});
	test.add(std::forward_list<uint8_t>{1, 2, 4});
	test.add(std::forward_list<uint8_t>{2, 1});
	test.add(std::forward_list<uint8_t>{2, 1, 1});

	assert(test.resolve(std::forward_list<uint8_t>{1, 2})    != nullptr);
	assert(test.resolve(std::forward_list<uint8_t>{1, 2, 4}) != nullptr);
	assert(test.resolve(std::forward_list<uint8_t>{3})       == nullptr);
}