algorithm - Converting a number to its equivalent in a specific range -


i have difficulties doing something, want convert number "equivalent" in given range.
although concept simple, it's pretty hard explain i'll best.

let's have got infinite row of tiles, although there infinite number of tiles, it's exact same color pattern repeats, : a row of coloured tiles, same color pattern repeating again , again. each tile has number.

as can see, have given number each tile, take range, going 0 4, , : 0 purple
1 blue
2 red
3 green
4 yellow

but because color pattern repeats infinitely, actually, 5 have same color 0, 6 have same color 1, 8 have same color 3.
also, must not forget negative numbers, -1 have same color 4 example.

actually want convert given number number of range have choosen, here range [0;4] know colour corresponds particular tile.
want method work other ranges, example should work if range [1;5] or [-7;-3].

i have found method works [0;n] ranges (with n positive integer), , a positive integer :

convertednumber = % (n+1) 

here's gives playground : we doing conversion, behaves expected

but works conditions described, , after hours struggling it, still can't find solution make work number, positive or negative, , range.

don't hesitate ask more details in comments.

thank you.

here go. function takes number want mapped, , low , high values of range , returns value in range:

func mapnum(n: int, low lo: int, high hi: int) -> int {     let spread = hi - lo + 1     return ((n - lo) % spread + spread) % spread + lo } 

examples:

mapnum(-9, low: 0, high: 4)    // returns "1" mapnum(-9, low: -3, high: 1)   // returns "1" mapnum(1, low: -11, high: -7)  // returns "-9" mapnum(3, low: -8, high: -4)   // returns "-7" mapnum(-5, low: 4, high: 8)    // returns "5" mapnum(-5, low: -6, high: -2)  // returns "-5" mapnum(-9, low: -7, high: -3)  // returns "-4" 

Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -