0

Given a value n, what would be the most efficient way of putting it in the range of [min, max] such that it will repeat through the range if it goes beyond it?

I don't know the term for this, so it's difficult to phrase the question, but maybe a truth table might help:

Where min = -2 and max = 3

 input  --> output
    -6      0
    -5      1
    -4      2
    -3      3
    -2     -2
    -1     -1
     0      0
     1      1
     2      2
     3     -2
     4     -1
     5      0
     6      1  

What I have so far is this:

(value - min) % (max - min) + min;

Which works, but my worry is the modulus operator % is unreliable for negative inputs, from what I've read (output becomes implementation defined, rendering it useless, or at least unportable)

Anne Quinn
  • 12,609
  • 8
  • 54
  • 101

2 Answers2

1

it is like this:

min = VALUE;
max = VALUE;
x = (((x - min) + 1) % (max - min)) + min

here x will be inside min and max - 1 when you repeat the last line of code

EDIT:

and to match your exact table:

output = (input - min) % (max - min) + min;

EDIT 2:

if modulus is not defined for negative numbers:

if (input >= min)
    output = (input - min) % (max - min) + min;
else
    output = max - ((max - input) % (max - min));
ammcom
  • 992
  • 1
  • 7
  • 24
  • Will this work if `(input - min)` results in a negative number? I've read in C/C++, modulus on negative numbers isn't defined by the language (the sign of the result might be negative) – Anne Quinn Jun 14 '16 at 07:08
0

If I understood your request correctly, here's the simplest equation i could think of : x % (max - min) + min

And here you can find some ways to optimize the modulo operator.

Community
  • 1
  • 1
Zohar81
  • 4,554
  • 5
  • 29
  • 82