[英]How to encode/decode all combinations of 2 integers in another one
i want to encode all possible directions of a square into an integer (except the 0,0).我想将正方形的所有可能方向编码为 integer(0,0 除外)。
i have two directions i, j
each one could be {-1, 0, 1}
我有两个方向
i, j
每个可以是{-1, 0, 1}
i need 2 functions with these signatures我需要 2 个带有这些签名的函数
int encodeToIndex(int i, int j) {
}
and和
int[] decodeFromIndex(int x) {
}
We could use a Hashmap, but i need an optimized solution, we should be able to encode all the combinations (except the 0,0) in just 8 numbers from 0 to 7 (i need an index from 0 to 7).我们可以使用 Hashmap,但我需要一个优化的解决方案,我们应该能够将所有组合(0,0 除外)编码为从 0 到 7 的 8 个数字(我需要从 0 到 7 的索引)。
I am working with JAVA, so a JAVA solution would be prefered (but it a mathematical problem).我正在使用 JAVA,因此首选 JAVA 解决方案(但这是一个数学问题)。
folowing the @Andrea solution i choose this solution for the moment:遵循@Andrea 解决方案,我暂时选择此解决方案:
public static int encode(int i, int j) {
int res = (i + 1) + (j + 1) * 3;
return res>4?res-1:res;
}
public static int[] decode(int x) {
if (x>3) x++;
return new int[]{ x%3-1, x/3-1 };
}
You have 3 values for each, so one way to store that is to use 2 bits, eg use i + 1
(0-2) and j + 1
(0-2), then combined them using bit-manipulation:每个都有 3 个值,因此一种存储方法是使用 2 位,例如使用
i + 1
(0-2) 和j + 1
(0-2),然后使用位操作将它们组合:
(i + 1) | (j + 1) << 2
A more condensed result can be done by multiply by 3 instead:可以通过乘以 3 来获得更简洁的结果:
(i + 1) + (j + 1) * 3
For the various values of i
and j
that would produce:对于将产生的
i
和j
的各种值:
Bit-shift Factor of 3
i -1 0 1 i -1 0 1
j ┌───────── j ┌─────────
-1 │ 0 1 2 -1 │ 0 1 2
0 │ 4 5 6 0 │ 3 4 5
1 │ 8 9 10 1 │ 6 7 8
The reverse operation is simple enough too, using either bit-shift/-mask, or division/remainder.反向操作也很简单,使用位移/掩码或除法/余数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.