我有这段代码需要根据给定的Double distance
输入返回一个索引:
public static int calculateHashPrecision(Double reference) {
double[][] ranges = {
{0.037, 0.018},
{0.149, 0.149},
{1.19, 0.6},
{4.47, 4.78},
{38.2, 19.1},
{152.8, 152.8},
{1200, 610},
{4900, 4900},
{39000, 19500},
{156000, 156000},
{1251000, 625000},
{5004000, 5004000},
};
return 6;
}
假设传递的reference
的值是1000
,所以它落在1200, 610
范围内,因此此函数应返回索引6。对此的最佳实现是什么功能?
更新: 而且如果它不在特定的硬编码范围内,它将返回最接近的那个。
答案 0 :(得分:2)
对于每个循环,您都可以更快,更快速地完成
int index = 0;
for(double[] range: ranges){
if( range[1] < reference && reference < range[0]){
return index;
}
index ++;
}
答案 1 :(得分:1)
public static int calculateHashPrecision(Double reference) {
double[][] ranges = {
{0.037, 0.018},
{0.149, 0.149},
{1.19, 0.6},
{4.47, 4.78},
{38.2, 19.1},
{152.8, 152.8},
{1200, 610},
{4900, 4900},
{39000, 19500},
{156000, 156000},
{1251000, 625000},
{5004000, 5004000},
};
int maxValueIndexInRaw = 0;
int minValueIndexInRaw = 1;
for (int i = 0; i < ranges.length; i++) {
if (reference >=ranges[i][minValueIndexInRaw] && reference <= ranges[i][maxValueIndexInRaw] ) {
return i;
}
}
return -1;
}
答案 2 :(得分:0)
public static int calculateHashPrecision(double reference) {
double[][] ranges = {
{0.037, 0.018},
{0.149, 0.149},
{1.19, 0.6},
{4.47, 4.78},
{38.2, 19.1},
{152.8, 152.8},
{1200, 610},
{4900, 4900},
{39000, 19500},
{156000, 156000},
{1251000, 625000},
{5004000, 5004000},
};
// search through the array of ranges, and return the first index it falls into
for (int i = 0; i < ranges.length; i++) {
double[] rng = ranges[i];
// ranges as given have the higher number first, lower number second
// adjust this logic as necessary
double rng_bottom = rng[1];
double rng_top = rng[0];
if (rng_bottom < reference && reference < rng_top) {
return i;
}
}
// if no range contains the reference, e.g. for the number 6000, then return -1
return -1;
}
您可能需要仔细检查您的范围,以确保它们被正确编码。您是说一半的人都具有相同的开始和结束吗?
答案 3 :(得分:0)
如果数据已排序,则可以使用二进制搜索
int hi = ranges.length - 1, lo = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
int cmp = Double.compare(ranges[mid][0], reference);
if (cmp > 0 || cmp == 0) {
if (ranges[mid][1] <= reference) return mid;
else hi = mid - 1;
} else if (cmp < 0) {
lo = mid + 1;
}
}
return -1;