0

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.

Ashish Panwar
  • 1,118
  • 3
  • 11
  • 18
  • 2
    Please add the relevant programming language tag to your question. – Oliver Charlesworth Jan 05 '18 at 03:18
  • 2
    I'm voting to close this question as off-topic because in its current state, it's not about programming. – David Z Jan 05 '18 at 03:21
  • Is it given that the nth element is _n_*15? – Davis Herring Jan 05 '18 at 03:23
  • If the list contains 10 and multiples of 15, then you can divide the given number by 15, the quotient that you get can be used to find the number closest to given number, one edge case though if the number is less than 15 then calculate it's absolute difference from 10 and 15 both to find out to which of them is it closer to – tkhurana96 Jan 05 '18 at 03:24
  • if the list contains all multiples of 15 then it boils down to rounding to the nearest multiple of 15 https://stackoverflow.com/q/3407012/995714 https://stackoverflow.com/q/29557459/995714 https://stackoverflow.com/q/44116820/995714 anyway without a language tag it's not about programming and the question becomes invalid – phuclv Jan 05 '18 at 03:28

2 Answers2

1

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);
fubar
  • 16,918
  • 4
  • 37
  • 43
0

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.

SergGr
  • 23,570
  • 2
  • 30
  • 51