可以将一系列值映射到键的数据结构? [英] Data structures that can map a range of values to a key?

查看:171
本文介绍了可以将一系列值映射到键的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一个数据结构,从一系列值获取特定的值,并将其映射到一个键。



例如,我有以下条件:


  1. 从1到2.9,我想将其映射到A。

  2. 从4到6,我想把它映射到B。

  3. 从6.5到10,我想把它映射到C。

我的值为5,我想将其映射到一个键。所以基于上述条件,我应该将其映射到B。



Java中有没有任何人可以推荐我来解决问题的数据结构? >

目前,我正在使用只能将值映射到键的哈希表。我尝试将值的范围映射到哈希表中存在的特定值。但是,我将值范围映射到一个特定的值。所以现在我试图做另一种方法来将值的范围映射到一个键。有没有人有任何想法如何解决这个问题?



编辑:



感谢Martin Ellis,决定使用TreeMap来解决问题。

解决方案

你的范围是不重叠的吗?如果是,您可以使用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);

查找逻辑有点复杂,你可能想要一个包容性查找(即2.9地图到'A',而不是未定义):

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

示例:

  mappedValue(m,5)=='B'

更多结果包括:

  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


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.

解决方案

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

这篇关于可以将一系列值映射到键的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆