Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/DynamicDataDisplay/Common/RingDictionary.cs @ 13757

Last change on this file since 13757 was 12503, checked in by aballeit, 10 years ago

#2283 added GUI and charts; fixed MCTS

File size: 1.3 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Diagnostics.Contracts;
6
7namespace Microsoft.Research.DynamicDataDisplay.Common
8{
9  /// <summary>
10  /// Represents a dictionary with automatic removal of old values.
11  /// </summary>
12  /// <typeparam name="T"></typeparam>
13  public sealed class RingDictionary<T>
14  {
15    private int startGeneration = 0;
16    private int generation;
17    private readonly Dictionary<int, T> dict = new Dictionary<int, T>();
18    private readonly int maxElements = 5;
19
20    public RingDictionary(int maxElements = 5)
21    {
22      Contract.Assert(maxElements >= 1);
23
24      this.maxElements = maxElements;
25    }
26
27    public int Generation
28    {
29      get { return generation; }
30    }
31
32    public int StartGeneration
33    {
34      get { return startGeneration; }
35    }
36
37    public bool ContainsValue(T value)
38    {
39      return dict.ContainsValue(value);
40    }
41
42    public void AddValue(T value)
43    {
44      Contract.Assert(value != null);
45
46      dict.Add(generation++, value);
47      Cleanup();
48    }
49
50    public int Count
51    {
52      get { return dict.Count; }
53    }
54
55    private void Cleanup()
56    {
57      while ((generation - startGeneration) > maxElements)
58      {
59        dict.Remove(startGeneration);
60        startGeneration++;
61      }
62    }
63  }
64}
Note: See TracBrowser for help on using the repository browser.