Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data structures that can map a range of keys to a value

Tags:

I am trying to find a data structure that takes in a particular value from a range of values and map it to a key.

For example, I have the following conditions:

  1. From 1 to 2.9, I want to map it to A.
  2. From 4 to 6, I want to map it to B.
  3. From 6.5 to 10, I want to map it to C.

I have a value of 5 and I would like to map it to a key. So based on the above conditions, I should map it to B.

Is there any data structure in Java that anyone can recommend to me to solve the problem?

Currently I am using a hashtable that can only map a value to a key. I tried to map the range of values to a particular value that exists in the hashtable. However, I got stuck in the mapping of the range of values to a particular value. So now I am trying to do another way of mapping the ranges of values to a key. Does anyone have any idea how I can solve this problem?

EDIT:

Thanks to Martin Ellis, I decided to use TreeMap to solve the problem.

like image 982
Sakura Avatar asked Nov 15 '12 14:11

Sakura


People also ask

Which data structure is used to map keys to values?

Hash maps are a common data structure used to store key-value pairs for efficient retrieval. A value stored in a hash map is retrieved using the key under which it was stored.

What is the best data structure for mapping multiple keys to the same value?

HashMap will store separate references per key, but they can all point to the same reference.

Which technique used for mapping of keys?

The Map. keys() method is used to extract the keys from a given map object and return the iterator object of keys. The keys are returned in the order they were inserted. Parameters: This method does not accept any parameters.

What is mapping in data structure?

• A Map is an abstract data structure (ADT) • it stores key-value (k,v) pairs. • there cannot be duplicate keys. • Maps are useful in situations where a key can be viewed as a unique identifier for the object. • the key is used to decide where to store the object in the structure.


1 Answers

Are your ranges non-overlapping? If so you could use a TreeMap:

TreeMap<Double, Character> m = new TreeMap<Double, Character>(); m.put(1.0, 'A'); m.put(2.9, null); m.put(4.0, 'B'); m.put(6.0, null); m.put(6.5, 'C'); m.put(10.0, null); 

The lookup logic is a bit complicated by the fact that you probably want an inclusive lookup (i.e. 2.9 maps to 'A', and not undefined):

private static <K, V> V mappedValue(TreeMap<K, V> map, K key) {     Entry<K, V> e = map.floorEntry(key);     if (e != null && e.getValue() == null) {         e = map.lowerEntry(key);     }     return e == null ? null : e.getValue(); } 

Example:

mappedValue(m, 5) == 'B' 

More results include:

0.9 null 1.0 A 1.1 A 2.8 A 2.9 A 3.0 null 6.4 null 6.5 C 6.6 C 9.9 C 10.0 C 10.1 null 
like image 170
Martin Ellis Avatar answered Jan 11 '23 18:01

Martin Ellis