2

Saby people, I'm trying to write the function which will map

this -->    ...-5|-4|-3|-2|-1| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9...
to this --> ... 3| 0| 1| 2| 3| 0| 1| 2| 3| 0| 1| 2| 3| 0| 1... 

Ideally if I enter myFunc(-1,4) it will return 3 the second argument "4" here is how many numbers I want to be looping.

I found that modulus operator (%) Is doing it for positive integers , but I need it to work in all integers and cant found solution. Also I understood that what I need is the sawtooth discrete wave so I looked in wikipedia and really can't figure it out. Please help.

Manvel A.
  • 33
  • 5

1 Answers1

3

For those positive numbers, it's simple, as you've noted:

x % 4

For negative numbers, what you need to do is shift that whole line forward to be positive, and then modulus. Try this, which works how you want for both positive and negative:

(x % 4 + 4) % 4
Brad
  • 159,648
  • 54
  • 349
  • 530