Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-value dictionary which returns any of the value for a specific key

I need to create a dictionary that has 2 values per key, and it must return one of the 2 values with the same probability.

Example:

myDicry
{
  key = "A", value1=15, value2=56;
}

int firstCall = myDicry["A"];  // = 15
int secondCall = myDicry["A"]; // = 56
like image 670
ZAA Avatar asked Dec 10 '25 22:12

ZAA


2 Answers

It would be possible to write an IDictionary<TKey, TValue> implementation that behaved in this manner, but that would not be a good idea: most people would find a non-deterministic indexer for a collection-class very unintuitive.

Instead, I suggest you make this the responsibility of the value for a key, rather than the Dictionary itself. One option would be to write a custom-type that is capable of picking from a set of possibilities with equal probability. For example:

public class UnbiasedRandomPicker<T>
{
    private readonly Random _rand = new Random();
    private readonly T[] _possibilities;

    public UnbiasedRandomPicker(params T[] possibilities)
    {
        // argument validation omitted
        _possibilities = possibilities;
    }

    public T GetRandomValue()
    {
        return _possibilities[_rand.Next(_possibilities.Length)];
    }
}

You could then use the dictionary like this:

var dict = new Dictionary<string, UnbiasedRandomPicker<int>>
{
    {"A", new UnbiasedRandomPicker<int>(15, 56)},
    {"B", new UnbiasedRandomPicker<int>(25, 13)}
};

int randomValueFromA = dict["A"].GetRandomValue();
like image 199
Ani Avatar answered Dec 12 '25 12:12

Ani


There's nothing built into the framework to do this, but you'd probably want to implement it by creating a "wrapper" type which had a Dictionary<TKey, Tuple<TValue, TValue>>. You'd then write an indexer to choose appropriately between the two values.

like image 40
Jon Skeet Avatar answered Dec 12 '25 11:12

Jon Skeet