Skip to content

Instantly share code, notes, and snippets.

@panicoenlaxbox
Last active August 29, 2019 18:19
Show Gist options
  • Save panicoenlaxbox/377f15d1d695d906eea625f41dd1578f to your computer and use it in GitHub Desktop.
Save panicoenlaxbox/377f15d1d695d906eea625f41dd1578f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Func<int, int> factorial = null;
factorial = Memoize<int, int>(n =>
{
Console.WriteLine($"Working for factorial {n}");
if (n == 1)
{
return 1;
}
return n * factorial(n - 1);
});
ExecuteFactorialExample(factorial);
var sum = Memoize<int[], int>(array =>
{
Console.WriteLine($"Working for sum {string.Join(",", array)}");
return array.Sum();
});
ExecuteSumExample(sum);
}
private static void ExecuteSumExample(Func<int[], int> sum)
{
Console.WriteLine(sum(new[] { 3 }));
Console.WriteLine(sum(new[] { 4, 5 }));
Console.WriteLine(sum(new[] { 3 }));
Console.WriteLine(sum(new[] { 4, 5 }));
Console.WriteLine(sum(new[] { 5, 6, 7 }));
//Memoize
//[3] not found in cache
//Working for sum 3
//3
//[4,5] not found in cache
//Working for sum 4,5
//9
//[3] found in cache
//3
//[4,5] found in cache
//9
//[5,6,7] not found in cache
//Working for sum 5,6,7
//18
}
private static void ExecuteFactorialExample(Func<int, int> factorial)
{
Console.WriteLine(factorial(3));
Console.WriteLine(factorial(3));
Console.WriteLine(factorial(4));
Console.WriteLine(factorial(3));
//Memoize
//3 not found in cache
//Working for factorial 3
//2 not found in cache
//Working for factorial 2
//1 not found in cache
//Working for factorial 1
//6
//3 found in cache
//6
//4 not found in cache
//Working for factorial 4
//3 found in cache
//24
//3 found in cache
//6
}
public static Func<T, TResult> Memoize<T, TResult>(Func<T, TResult> fn)
{
Console.WriteLine(nameof(Memoize));
var cache = new Dictionary<string, TResult>();
return n =>
{
var key = JsonConvert.SerializeObject(n);
if (cache.ContainsKey(key))
{
Console.WriteLine($"{key} found in cache");
return cache[key];
}
Console.WriteLine($"{key} not found in cache");
var value = fn(n);
cache[key] = value;
return value;
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment