-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmemoizer.cpp
More file actions
41 lines (39 loc) · 960 Bytes
/
memoizer.cpp
File metadata and controls
41 lines (39 loc) · 960 Bytes
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
#include <iostream>
#include <functional>
#include <unordered_map>
#include <string>
template<typename R, typename P>
class Memoizer {
constexpr R f(const P& n) {
if (n < 2) {
return n;
}
else {
return call(n - 2) + call(n - 1);
}
}
std::unordered_map<P,R> m;
public:
R call(const P& param) {
if (auto iter = m.find(param); iter != m.end()) {
return iter->second;
}
else {
auto r = f(param);
m.insert({ param, r });
return r;
}
}
};
int main(const int argc, const char **argv) {
Memoizer<long long,long long> m;
if (argc == 2) {
auto n = std::stoll(argv[1]);
std::cout << "Fibonacci(" << n << "): " << m.call(n) << '\n';
}
else {
for (long long n = 0; n != 50; ++n) {
std::cout << "Fibonacci(" << n << "): " << m.call(n) << '\n';
}
}
}