Search code examples
c#.netdictionarylookup

A dictionary object that uses ranges of values for keys


I have need of a sort of specialized dictionary. My use case is this: The user wants to specify ranges of values (the range could be a single point as well) and assign a value to a particular range. We then want to perform a lookup using a single value as a key. If this single value occurs within one of the ranges then we will return the value associated to the range.

For example:

// represents the keyed value
struct Interval
{
    public int Min;
    public int Max;
}

// some code elsewhere in the program
var dictionary = new Dictionary<Interval, double>();
dictionary.Add(new Interval { Min = 0, Max = 10 }, 9.0);
var result = dictionary[1];
if (result == 9.0) JumpForJoy();

This is obviously just some code to illustrate what I'm looking for. Does anyone know of an algorithm to implement such a thing? If so could they point me towards it, please?

I have already tried implementing a custom IEqualityComparer object and overloading Equals() and GetHashCode() on Interval but to no avail so far. It may be that I'm doing something wrong though.


Solution

  • A dictionary is not the appropriate data structure for the operations you are describing.

    If the intervals are required to never overlap then you can just build a sorted list of intervals and binary search it.

    If the intervals can overlap then you have a more difficult problem to solve. To solve that problem efficiently you'll want to build an interval tree:

    http://en.wikipedia.org/wiki/Interval_tree

    This is a well-known data structure. See "Introduction To Algorithms" or any other decent undergraduate text on data structures.