[英]How to find the closest value of N no. into the sequence?
I have a list of integer sequence: 我有一个整数序列列表:
[10,15,30,45,60,75,90......n*15] [10,15,30,45,60,75,90 ...... N * 15]
Let's say you have a value ie 33 What calculation i should do to find the closest value of 33 into the above sequence? 假设您有一个值,即33,我应该怎么做才能在上述序列中找到最接近的33值? (JavaScript) Can we find it without loop?
(JavaScript)我们可以找到没有循环的东西吗?
Thanks. 谢谢。
As others have already pointed out, if you're working with multiples of 15
(assuming the sequence starting with 10
was a mistake), then you can simply do the following: 正如其他人已经指出的那样,如果您使用
15
倍数(假设以10
开头的序列是错误的),那么您可以简单地执行以下操作:
var interval = 15; var value = 33; var closest = Math.round(value / interval) * interval; console.log(closest);
You didn't specify any language, so here is some pseudocode. 您没有指定任何语言,所以这里是一些伪代码。 Also I assume that the sequence is actually
15*n
and there has to be 0
instead of 10
as the first element. 我还假设序列实际上是
15*n
,并且必须将0
而不是10
作为第一个元素。 Assume the sequence is form 0
to 15*N
and the test value is test
. 假设序列的形式为
0
到15*N
,测试值为test
。 IMHO, the simplest algorithm is following: 恕我直言,最简单的算法如下:
if(test <= 0)
return 0
else if (test >= 15*N)
return 15*N
else {
lower = Math.floor(test/15)
upper = lower + 1
lowerDif = test - 15*lower
upperDif = 15*upper - test
if (lowerDif < upperDif)
return 15*lower
else
return 15*upper
}
The idea is that you need to check if test
is inside [0; 15*N]
这个想法是,您需要检查
test
是否在[0; 15*N]
[0; 15*N]
range. [0; 15*N]
范围。 If no - return the boundary, else check two values at indices Math.floor(test/15)
and Math.floor(test/15) + 1
. 如果否,则返回边界,否则检查索引
Math.floor(test/15)
和Math.floor(test/15) + 1
处的两个值。 It is true that 的确
Math.floor(test/15) <= test < Math.floor(test/15) + 1
So whichever is closer is the answer. 因此,答案越近越好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.