Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a nearest-key map datastructure?

I have a situation where I need to find the value with the key closest to the one I request. It's kind of like a nearest map that defines distance between keys.

For example, if I have the keys {A, C, M, Z} in the map, a request for D would return C's value.

Any idea?

like image 591
oconnor0 Avatar asked Sep 03 '09 23:09

oconnor0


People also ask

Which data structure is used for map?

The map data type is referred to as an associative array because, like an array, it is a collection of values rather than a single value, as an Int or a String is. Furthermore, each distinct key is associated with a value, resulting in an associative array.

Is a map a data structure?

A Map is a type of fast key lookup data structure that offers a flexible means of indexing into its individual elements.

Is map a data structure in Java?

A map is a data structure that's designed for fast lookups. Data is stored in key-value pairs with every key being unique. Each key maps to a value hence the name. These pairs are called map entries.


2 Answers

Most tree data structures use some sort of sorting algorithm to store and find keys. Many implementations of such can locate a close key to the key you probe with (usually it either the closest below or the closest above). For example Java's TreeMap implements such a data structure and you can tell it to get you the closest key below your lookup key, or the closest key above your lookup key (higherKey and lowerKey).

If you can calculate distances (its not always easy - Java's interface only require you to know if any given key is "below" or "above" any other given key) then you can ask for both closest above and closest below and then calculate for yourself which one is closer.

like image 150
Guss Avatar answered Sep 20 '22 13:09

Guss


What's the dimensionality of your data? If it's just one dimensional, a sorted array will do it - a binary search will locate the exact match and/or reveal betweeen which two keys your search key lies - and a simple test will tell you which is closer.

If you need to locate not just the nearest key, but an associated value, maintain an identically sorted array of values - the index of the retrieved key in the key array is then the index of the value in the value array.

Of course, there are many alternative approaches - which one to use depends on many other factors, such as memory consumption, whether you need to insert values, if you control the order of insertion, deletions, threading issues, etc...

like image 35
Eamon Nerbonne Avatar answered Sep 19 '22 13:09

Eamon Nerbonne