-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclimbing_stairs.cpp
70 lines (58 loc) · 1.57 KB
/
climbing_stairs.cpp
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
/**
This is NOT a correct solution! The output from countClimbingStairs overflows if the input n is large enough.
To solve this, we would need a bigint library. Otherwise, the solution is a correct memoized fibonacci, FWIW.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
std::map<int, unsigned long long int> cache;
unsigned long long int countClimbingStairs(int n) {
// This is the same as fibonacci(n), actually
// We should do it in closed form
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
if (cache[n] > 0) {
return cache[n];
} else {
int res = countClimbingStairs(n - 2) + countClimbingStairs(n - 1);
cache[n] = res;
return res;
}
}
int main(int argc, char *argv[])
{
std::ifstream file;
std::string lineBuffer;
if (argc < 2) {
std::cout << "Please add the name of the file to process." << std::endl;
exit(1);
}
file.open(argv[1], std::ifstream::in);
for (int j = 0; j < 100; j++) {
if (cache[j] > 0) {
std::cout << j << " is not zeroed" << std::endl;
}
}
while (!file.eof())
{
getline(file, lineBuffer);
if (lineBuffer.length() == 0)
continue;
else
{
std::istringstream iss(lineBuffer);
int val;
iss >> val;
std::cout << val << " " << countClimbingStairs(val) << std::endl;
}
}
return 0;
}