[英]Map sequence of integers into repeating sequence
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
. 例如
...,-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
. 我需要将它们映射到重复序列
3,6,9,12
,初始条件为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. 因此例如
f(-2)=9, f(-1)=12, f(0)=3, f(1)=6, f(2)=9, f(3)=12, f(4)=3
,依此类推。 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? 是否有一种紧凑的方式来用Java表达此操作,以便我们能够仅使用剩余(%)运算符并避免任何if / else语句?
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 ) (原谅我任何语法错误,我尝试了PHP中的代码,并将其更改为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. 适用于正,负和每个fZero作为初始映射条件。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.