Ok, this is for a homework assignment, so please just try to direct me without giving me the straight-up answer.
I'm trying to institute memoization with the Ackermann function (C++). It does not do what I would expect when reaching Ackermann(1,2). Something tells me that I should maybe be trying to institute a map
instead of an array
for the memoization? Any input is appreciated.
#include <iostream>
using namespace std;
static int ackerMemoization[1000];
int acker(int m, int n)
{
if (m == 0)
return n + 1;
if (n == 0)
return acker(m - 1, 1);
if (ackerMemoization[m] != 0)
return ackerMemoization[m - 1];
else
{
ackerMemoization[m] = acker(m - 1, acker(m, n - 1));
return ackerMemoization[m];
//return acker(m - 1, acker(m, n - 1));
}
}
int main()
{
for (int i = 0; i < 1000; i++)
{
ackerMemoization[i] = 0;
}
//cout << "Ackermann(3, 20) = " << acker(3, 20) << endl;
//cout << "Ackermann(4, 0) = " << acker(4, 0) << endl;
//cout << "Ackermann(4, 1) = " << acker(4, 1) << endl;
for (int m = 0; m <= 4; ++m)
{
for (int n = 0; n < 20; ++n)
{
cout << "Ackermann(" << m << ", " << n << ") = " << acker(m, n) << "\n";
}
}
cin.get();
return 0;
}
So below is my new approach. But I can't figure out why I can't use memoMap.insert(make_pair(m, n), (acker(m - 1, 1)));
from within my acker
function??
#include <iostream>
#include <map>
using namespace std;
static map<pair<int, int>, int> memoMap;
int acker(int m, int n)
{
if (m == 0)
return n + 1;
if (n == 0)
{
//memoMap.emplace[make_pair(m, n), (acker(m - 1, 1)];
memoMap.insert(make_pair(m, n), (acker(m - 1, 1)));
return acker(m - 1, 1);
}
else
{
return acker(m - 1, acker(m, n - 1));
}
}
int main()
{
//static map<pair<int, int>, int> memoMap;
//cout << "Ackermann(3, 20) = " << acker(3, 20) << endl;
//cout << "Ackermann(4, 0) = " << acker(4, 0) << endl;
//cout << "Ackermann(4, 1) = " << acker(4, 1) << endl;
for (int n = 0; n <= 20; ++n)
{
cout << "Ackermann(" << 0 << ", " << n << ") = " << acker(0, n) << endl;
}
cout << endl;
for (int n = 1; n <= 20; ++n)
{
cout << "Ackermann(" << 1 << ", " << n << ") = " << acker(1, n) << endl;
}
cout << endl;
for (int n = 2; n <= 20; ++n)
{
cout << "Ackermann(" << 2 << ", " << n << ") = " << acker(2, n) << endl;
}
cout << endl;
for (int n = 3; n <= 20; ++n)
{
cout << "Ackermann(" << 3 << ", " << n << ") = " << acker(3, n) << endl;
}
cout << endl;
for (int n = 4; n <= 2; ++n)
{
cout << "Ackermann(" << 4 << ", " << n << ") = " << acker(4, n) << endl;
}
cin.get();
return 0;
}