-
-
Save collinsauve/abe22dd74b4367b42fd6 to your computer and use it in GitHub Desktop.
Generic Memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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