// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public class X { private int v; public X() : this(0) { } public X(int v) { this.v = v; } public int V { get { return v; } set { v = value; } } } public interface XFactory { X CreateX(int v); } public class NewXFactory : XFactory { public X CreateX(int v) { return new X(v); } } public interface Cache { X Lookup(int v); double HitRate { get; } } public abstract class BaseCache : Cache { private X[] data; private XFactory xf; private int hits; private int total; public BaseCache(int siz, XFactory xf) { data = new X[siz]; this.xf = xf; hits = 0; total = 0; } public abstract int PickSlot(int siz); public X Lookup(int v) { total++; for(int i = 0; i < data.Length; i++) { if(data[i] != null && data[i].V == v) { hits++; return data[i]; } } X o = xf.CreateX(v); data[PickSlot(data.Length)] = o; return o; } public double HitRate { get { return hits/(double)total; } } } public class RandomCache : BaseCache { private static Random rng = new Random(); public RandomCache(int siz, XFactory xf) : base(siz, xf) { } public override int PickSlot(int siz) { return rng.Next(siz); } } public class CircularCache : BaseCache { private static int last = -1; public CircularCache(int siz, XFactory xf) : base(siz, xf) { } public override int PickSlot(int siz) { last = (last + 1) % siz; return last; } } public class MainClass { private static Random rng = new Random(); public static void Test(string title, Cache cac, int popsiz, bool systematic) { for(int i = 0; i < 10000; i++) { int v; if(systematic) { v = (i % popsiz + rng.Next(11) - 5 + popsiz) % popsiz; } else { v = rng.Next(popsiz); } X o = cac.Lookup(v); if(o.V != v) { Console.WriteLine("Oops"); Environment.Exit(0); } } Console.WriteLine(title + " : " + cac.HitRate); } public static void Main(string[] args) { Test("Random cache & random data ", new RandomCache(10, new NewXFactory()), 50, false); Test("Random cache & repeat data ", new RandomCache(10, new NewXFactory()), 50, true); Test("Circular cache & random data", new CircularCache(10, new NewXFactory()), 50, false); Test("Circular cache & repeat data", new CircularCache(10, new NewXFactory()), 50, true); } } }