Skip to content

@collinsauve /GenericMemoization.cs secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.