I have a continuous, ordered sequence of integers that start less than zero and go above zero; for instance ...,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7
. I need to map these into a repeating sequence 3,6,9,12
, with the initial condition that f(0)=3
. So for instance f(-2)=9, f(-1)=12, f(0)=3, f(1)=6, f(2)=9, f(3)=12, f(4)=3
and so on. Is there a compact way to express this operation in Java, so that we are able to just use the remainder (%) operator and avoid any if/else statements?
This would server your purpose:
int repeatInt = 12 - ((11 - seqInt)*3) % 12 ;
where repeatInt = 3,9,6 or 12, the output
and seqInt = a number from your sequence
( forgive me for any syntax mistakes, I tried the code in PHP, and changed it to Java )
int repeatingSequence[] = { 3,6,9,12 };
int fZero = 0;
int len = repeatingSequence.length;
public int f(int n) {
return repeatingSequence[ (n % len + fZero + len) % len ];
}
Works for positives, negatives, and every fZero as the initial mapping condition.
I would suggest the following to handle negative numbers.
public int f(int n, int ... sequence) {
int idx = n % sequence.length;
if (idx < 0) idx += sequence.length;
return sequence[idx];
}
int x = f(n, 3,6,9,12);
however in this specific example there is a much simpler solution ;)
public int f(int n) {
return (n & 3) * 3 + 3;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.