I think this solution is quite simple, but I was thinking about this for a while and did not come With elegant solution.
I have many numbers, such as 1..10 = (1,2,3,4,5,6,7,8,9,10)
, which is the circular , Which means that for the first time after the last one ( Next (10) = 1
).
For a given number, i & gt; In the category, I want to do the next
-th, and the previous M
-common like Next (5,1) = 6
Next (10,1) = 1
Next (10,2) = 2
prev (5,2) = 3
Previous (1,1) = 10
prev (1,2) = 9
.
For Next
I can simply take (i + m)% n
where n
is the length of the border ( n = 10
in the example) but I could not find a great solution for previous
.
Simply subtract 1 and add 1 later.
In most programming languages, you need to search the "previous" value, because for the negative number, the modules do not work in this case as you want: this negative number.
Here is the C / C ++ version:
int next (int i, int m, int n) {return (i + m - 1)% n + 1; } Int prev (int i, int m, int n) {return (i - m + n - 1)% n + 1; }
However, Perl always gives a positive value in modulo (at least when the second operator is a positive integer). Basically, if you want it, you can write the following and + $ _ [2]
:
sub nxt {($ _ [0] + $ _ [1] - 1)% $ _ [2] + 1; } Sub PRV {($ _ [0] - $ _ [1] - 1)% $ _ [2] + 1; }
Comments
Post a Comment