我正在尝试做一个一维的Convay生命游戏计划,但是每当一代人通过时,程序就会继续产生额外的数字。代码:
int generation=IntegerparseInt(in.nextLine().trim());
long cells=Long.parseLong(input1, 2);
for(int i=0;i<generation;i++)//Assume
{
long newa=cells>>1;
long newb=cells<<1;
System.out.println(Long.toBinaryString(newb));//For testing purpose
cells=newa^newb;
System.out.println(Long.toBinaryString(cells));//For testing purpose
}
输入如
3
01011
(3代) 我得到像这样的输出
10110
10011
100110
101111
1011110
1001001
所需的输出是
10110
00011
00110
10111
01111
01011
编辑:将测试代码更改为:
for(int i=0;i<generation;i++)
{
long newa=cells>>1;
long newb=cells<<1;
System.out.println(Long.toBinaryString(newb));
System.out.println(Long.toBinaryString(newa));
cells=newa^newb;
System.out.println(Long.toBinaryString(cells));//For testing purpose
}
输出结果为:
10110
101
10011
100110
1001
101111
1011110
10111
1001001
答案 0 :(得分:2)
正如安德鲁所说,左移总是产生一个额外的数字。这实际上是一个正确的实现,因为康威的生命游戏发生在无限的宇宙中。但是,如果要限制Universe的大小,则只需要保留每一代的N个最右边的数字,其中N是Universe的大小。
如this answer中所述,可以通过操作K&((1<<N)-1)
完整的工作示例:
public class ConwaysGame {
public static void main(String[] args) {
int numGenerations = 10;
// Size of the "universe"
int universeSize = 12;
// Initial value
long cells = 29;
for(int i=0;i<numGenerations;i++) {
// Calculate new generation
long newa=cells>>1;
long newb=cells<<1;
cells=newa^newb;
// Limit the result to the size of the universe
cells = rightMostBits(cells, universeSize);
// Output to console
System.out.println(
leftPadZeros(
Long.toBinaryString(cells), universeSize
)
);
}
}
private static long rightMostBits(long data, int numBits){
// https://stackoverflow.com/questions/2798191/extracting-rightmost-n-bits-of-an-integer
return data & ((1<<numBits)-1);
}
private static String leftPadZeros(String str, int len){
int numzeros = Math.max(len - str.length(), 0);
return new String(new char[numzeros]).replace("\0", "0") + str;
}
}
输出:
000000110100
000001110010
000011011101
000111010100
001101000010
011100100101
110111011000
110101011100
110000010110
111000100111
答案 1 :(得分:1)
假设单元格为0111
。看看当你进行迭代时会发生什么:
cells = 0111
newa = 0011
newb = 1110
newa ^ newb = 1101
左移一个数字总是会产生一个额外的数字,因为你正在使用相同的右移数字XOR
,所以额外的数字将始终保留。