How can I randomly remove a key with value 0 efficiently ?
Dictionary<string, int> dict = new Dictionary<Edge, int>();
dict.add("a",0);
dict.add("b",0);
dict.add("c",0);
dict.add("d",1);
The size of dictionary is 10000.
How can I randomly remove a key with value 0 efficiently ?
Dictionary<string, int> dict = new Dictionary<Edge, int>();
dict.add("a",0);
dict.add("b",0);
dict.add("c",0);
dict.add("d",1);
The size of dictionary is 10000.
Something like this should do it:
IEnumerable<string, int> pairsToRemove = dictionary.Where(pair => pair.Value == 0);
To generate a random index, you could use:
int indexToRemove = [RandomNumber] % pairsToRemove.Length() -1;
Find the indexToRemove th element from pairsToRemove and remove it from the dictionary.
As to efficiency: The complexity should be O(n)[get all items with value 0] + O(.6N)[finding ith value to remove] + O(log(n))[deletion] assuming the random number generation is constant time.
The problem is, there is no way to perform a value lookup on a dictionary in better than O(n) time. So that will be your bottleneck.
This will remove the first item with a zero value. It's not precisely "random", but is non-deterministic.
Dictionary<string, int> dict = new Dictionary<string, int>();
string keyToRemove = null;
foreach (var kvp in dict)
{
if (kvp.Value == 0)
{
keyToRemove = kvp.Key;
break;
}
}
if (keyToRemove != null)
{
dict.Remove(keyToRemove);
}