Skip to content

Instantly share code, notes, and snippets.

@collinsauve
Created February 24, 2011 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save collinsauve/abe22dd74b4367b42fd6 to your computer and use it in GitHub Desktop.
Save collinsauve/abe22dd74b4367b42fd6 to your computer and use it in GitHub Desktop.
Generic Memoization
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharp2
{
class Program
{
private static FibCalc fibCalc = new FibCalc();
static void Main(string[] args)
{
Test(1, 1);
Test(2, 1);
Test(3, 2);
Test(9, 34);
Console.ReadKey();
}
public static void Test(int x, int expected)
{
int result = fibCalc.Fib(x);
string correct = (result == expected) ? "OK " : "ERROR ";
Console.WriteLine("{0}{1} -> {2}", correct, x, result);
}
public class FibCalc
{
private readonly Memoizer<int, int> _memoizer;
public FibCalc()
{
_memoizer = new Memoizer<int, int>((x) => { return Fib(x); });
}
public int Fib(int x)
{
if (x < 2)
return x;
else
return _memoizer.GetValue(x - 1) + _memoizer.GetValue(x - 2);
}
}
public class Memoizer<K, V>
{
private Dictionary<K, V> _memoized = new Dictionary<K, V>();
private Func<K, V> _func;
public Memoizer(Func<K, V> func)
{
_func = func;
}
public V GetValue(K key)
{
V value;
if (_memoized.TryGetValue(key, out value))
{
return value;
}
else
{
value = _func(key);
_memoized.Add(key, value);
return value;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment