Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Look up dictionary

Tags:

c#

I'm currently trying to create a program that estimates location based on signal strength. The signal strength value is an int and then i need a lookup dictionary with ranges.

So I would have something like:

Signal Strenth             Position
0-9                            1
10-19                          2
20-29                          3

and then I would want to look up what position a signal strength relates to, for example 15 would relate to position 2.

I know I can just have a load of if statements but is there a good way to do this using some sort of lookup dictionary?

like image 658
DNN Avatar asked Aug 31 '09 18:08

DNN


3 Answers

If you have arbitrary but consecutive ranges you can use an array of the upper bounds and perform a binary search to get the position:

// Definition of ranges
int[] ranges = new int[] { 9, 19, 29 };

// Lookup
int position = Array.BinarySearch(ranges, 15);
if (position < 0)
    position = ~position;

// Definition of range names
string[] names = new string[] { "home", "street", "city", "far away" };

Console.WriteLine("Position is: {0}", names[position]);

Array.BinarySearch returns the index of the item in the array if it exists (array must be sorted obviously) or the bitwise inverted index where the item should be inserted to keep the array sorted.

like image 173
dtb Avatar answered Nov 15 '22 06:11

dtb


What about :

int position = signalStrength / 10 + 1;

Kindness,

Dan

like image 32
Daniel Elliott Avatar answered Nov 15 '22 04:11

Daniel Elliott


When you want to use Dictionary, you need at least some special key type to deal with the ranges. KeyType can be abstract and two derived types KeyTypeRange(int int) and KEyTypeSearch( int). Some special comparison logic must be implemented to compare an KeyTypeSearch with an KeyTypeRange.

SortedDictionary<KeyType,int>  lookup = new Dictionary<int,int>();
lookup.Add( new KeyTypeRange(1,10),1);
lookup.Add( new KeyTypeRange(11,20),2);
lookup.Add( new KeyTypeRange(21,30),3);
lookup.TryGetValue( new KeyTypeSearch(15) );

It shows a possible solution to use different esearch keys and key values in dictionaries. But this seems to be Overkill for this problem. This problem is solved best by the BinarySearch solution.

like image 27
Thomas Maierhofer Avatar answered Nov 15 '22 04:11

Thomas Maierhofer