Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find out if number X is in range of number Y? (But in a circular way)

Imagine I have a range of numbers 0-9.
And I want to find out if number X is in range of number Y, and the range would be 2.

So for example with Y=5, X is in range if X is 3,4,5,6 or 7.

   --Y-- 
0123456789

For this I could do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

isInRange = abs(X - Y) <= 2

But I need it in a way, that the range is kind of circular, starting with 0 again:

     --Y--    -     --Y-    --     --Y    Y--     --    -Y--     -    --Y--
0123456789    0123456789    0123456789    0123456789    0123456789    0123456789

Someone an idea how to solve this?

>Solution :

This is in javascript, but should do the job in any language with some changes. Look that I’m taking the modulus of each number to make them in range [0, 9]

const isInRange = (x, y, range) => {
  const
    absDiff = Math.abs(x % 10 - y % 10),
    modRange = range % 10;
    
  return absDiff <= modRange || 10 - absDiff <= modRange;
}

console.log(isInRange(0, 9, 2))
console.log(isInRange(1, 9, 2))
console.log(isInRange(4, 7, 2))
console.log(isInRange(9, 7, 2))
console.log(isInRange(19, 7, 2))
console.log(isInRange(9, 7, 9))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading