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

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:

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 1:[1]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AlexSp3