secret
Created

Generic Memoization

  • Download Gist
GenericMemoization.cs
C#
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 71 72 73 74 75 76 77
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;
}
}
}
 
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.