4

How would I go about making a function so that x has a range of values from x=0 to x=19 and if the x value exceeds 19 or is below zero how can I get it to wrap around

From: x=20, x=21, x=22 and x=(-1), x=(-2), x=(-3)

To: x=0, x=1, x=2 and x=19, x=18, x=17 respectively?

I've heard of modular arithmetic which is apparently the way I should deal with it.

double-beep
  • 5,031
  • 17
  • 33
  • 41
maclunian
  • 7,893
  • 10
  • 37
  • 45

3 Answers3

7

Usually you would use the built-in functions mod and rem, but I assume they are off-limits for homework. So you can write your own function, e.g.

mod20 x | x < 0 = ...
        | x > 19 = ...
        | otherwise = x

There are different things you can try to fill in the ...s. One of the easiest is repeated addition or subtraction, but I don't want to spoil all the fun.

Once you have this function, you can "rescale" the values after every "normal" arithmetic operation, e.g. mod20 (12 + 17).

Landei
  • 54,104
  • 13
  • 100
  • 195
3

Try using the mod function:

(-5) `mod` 20 ==> 15
5 `mod` 20 ==> 5
20 `mod` 20 ==> 0
25 `mod` 20 ==> 5

See also wikipedia on the topic.

luqui
  • 59,485
  • 12
  • 145
  • 204
aleator
  • 4,436
  • 20
  • 31
1

Use

x `mod` 20

(This is a filler to make the answer 30 characters.)

augustss
  • 22,884
  • 5
  • 56
  • 93