Skip to content

Instantly share code, notes, and snippets.

@okaram
Last active October 13, 2015 10:08
Show Gist options
  • Save okaram/4179787 to your computer and use it in GitHub Desktop.
Save okaram/4179787 to your computer and use it in GitHub Desktop.
Recursion and memoization
unsigned factorial(unsigned n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
unsigned fibo(unsigned n)
{
if(n<=1)
return n;
return fibo(n-1)+fibo(n-2);
}
unsigned fibo_memo(unsigned n)
{
static map<unsigned,unsigned> memo;
if(n<=1)
return n;
if(memo.count(n)>0)
return memo[n];
// otherwise
unsigned ret=fibo_memo(n-1)+fibo_memo(n-2);
memo[n]=ret;
return ret;
}
int main(int argc, char*argv[])
{
fibo1=memoize(fibo1);
cout << argv[1] << " ->" << fibo1(atoi(argv[1])) << endl;
}
std::function<unsigned(unsigned)> fibo1=[](unsigned n)
{
if(n<=1)
return n;
return fibo1(n-1)+fibo1(n-2);
};
template<class InType, class OutType>
std::function<OutType(InType)> memoize(std::function<OutType(InType)> foo)
{
// return a lambda, this is a function
return [foo](InType n){
static map<InType,OutType> memo;
OutType ret;
if(memo.count(n)>0) {
ret =memo[n];
return ret;
}
ret=foo(n);
memo[n]=ret;
return ret;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment