Java 产生与3位代码仅相差一位的所有3位代码
我需要找到所有不同的3位代码。该扫描可以用3个嵌套的fro循环完成 我想取我生成的这个位代码数组,然后输出所有其他只相差一位的代码。所以我试着生成一个8*3的2d数组。我知道有3个代码只相差1位数,但我就是找不到一种方法来编码 这是我到目前为止所拥有的Java 产生与3位代码仅相差一位的所有3位代码,java,arrays,Java,Arrays,我需要找到所有不同的3位代码。该扫描可以用3个嵌套的fro循环完成 我想取我生成的这个位代码数组,然后输出所有其他只相差一位的代码。所以我试着生成一个8*3的2d数组。我知道有3个代码只相差1位数,但我就是找不到一种方法来编码 这是我到目前为止所拥有的 String[] codes = new String[8]; int count = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j
String[] codes = new String[8];
int count = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
codes[count] = "" + i + j + k;
count ++;
}
}
}
String[] code_1 = new String[3];
String[][] codesNear = new String[8][3];
for(int h = 0; h < codesNear.length; h ++){
for(int i = 0 ; i < codes[1].length() ;i ++){
if(codes[h].charAt(i) == '1' ){
if(i != 2)
codesNear[h][i] = codes[1].substring(0,i) + "0" + codes[1].substring(i+1);
else codesNear[h][i] = codes[1].substring(0,i) + "0";
}
else {
if(i != 2)
codesNear[h][i] = codes[1].substring(0,i) + "1" + codes[1].substring(i+1);
else codesNear[h][i] = codes[1].substring(0,i) + "1";
}
}
}
for (String s : codes) {
System.out.println(s);
}
count = 0;
for(String[] s : codesNear){
System.out.println("Count" + count + "Code " + codes[count]);
for(String st : s ){
System.out.println(st);
}
count ++;
}
}
正如你们所看到的,输出是不正确的。例如,对于000,thre输出应该是100010001而不是101011001
也可以将此代码读取一些数字n,然后找到n长二进制代码的所有不同可能性您可以通过将整数的最低3位转换为字符串的方法来简化此过程
String bitString(int n) {
return new String("" + ((n>>>2)&1) + ((n>>>1)&1) + (n & 1));
}
然后,您可以对每个位位置(1:001、2:010、4:100)都有1位的数字使用位异或。然而,这是有点难说,如果这是你希望从张贴的问题
String[][] codesNear = new String[8][4];
for(int i = 0; i < 8; i++) {
codesNear[i][0] = bitString(i);
codesNear[i][1] = bitString(i ^ 1);
codesNear[i][2] = bitString(i ^ 2);
codesNear[i][3] = bitString(i ^ 4);
}
您可以通过将整数的最低3位转换为字符串的方法来简化此过程
String bitString(int n) {
return new String("" + ((n>>>2)&1) + ((n>>>1)&1) + (n & 1));
}
然后,您可以对每个位位置(1:001、2:010、4:100)都有1位的数字使用位异或。然而,这是有点难说,如果这是你希望从张贴的问题
String[][] codesNear = new String[8][4];
for(int i = 0; i < 8; i++) {
codesNear[i][0] = bitString(i);
codesNear[i][1] = bitString(i ^ 1);
codesNear[i][2] = bitString(i ^ 2);
codesNear[i][3] = bitString(i ^ 4);
}
你在尝试生成格雷码吗?我在尝试建模一个数学问题,它涉及排列和组合的组合。我意识到我可以用二进制表示不同的组合,因此我认为计算机模拟所有不同的可能性要比手工操作容易得多。你是在尝试生成格雷码吗:?我在尝试模拟一个数学问题,它涉及排列和组合的组合。我意识到我可以用二进制来表达不同的组合,因此我认为计算机模拟所有不同的可能性比手工操作要容易得多。
String bitString(int n, int numBits) {
StringBuffer ret = new StringBuffer(numBits);
for(int i = numBits; i > 0; i--) {
ret.append((n>>>(i-1))&1);
}
return ret.toString();
}