I have a list of integer sequence:
[10,15,30,45,60,75,90......n*15]
Let's say you have a value i.e. 33 What calculation i should do to find the closest value of 33 into the above sequence? (JavaScript) Can we find it without loop?
Thanks.
I have a list of integer sequence:
[10,15,30,45,60,75,90......n*15]
Let's say you have a value i.e. 33 What calculation i should do to find the closest value of 33 into the above sequence? (JavaScript) Can we find it without loop?
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:
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. Assume the sequence is form 0
to 15*N
and the test value is 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]
range. If no - return the boundary, else check two values at indices Math.floor(test/15)
and 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.