HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

One-dimensional circular Conway's Game of Life

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conwayonegamecircularlifedimensional

Problem

I have a program that is working, but it takes way too long to get the answer. With input like

15 100000000
111010111001100


The program checks for 15 numbers, and checks if two number beside the numbers in the second row adds up to exactly 1. If it adds up to 1, then the number would stay/change to 1, otherwise it change/stay 0. And this need to happen for 100000000 times (it changes each time). Right now I can get the right answer, but it takes like 1 minute to get it.

```
import java.util.*;
public class circle {
final Scanner in;
public circle()
{
in=new Scanner(System.in);
run();
in.close();
}
public void run()
{
String input=in.nextLine();
//I created two arrays, checks for one array while change the other one so the changed number wouldn't affect other checking
final int[] list=createarray(input);
final int totalcells=list[0];
final int generation=list[1];
String input1=in.nextLine();
long[] deadalive=createarray2(input1,totalcells);
long[] changing=new long[totalcells];
System.arraycopy(deadalive,0,changing,0,totalcells);
//It checks for y times and checks all the cells
for(int y=0;y<generation;y++)
{
for(int x=0;x<totalcells;x++)
{
if(x==0)
{
if(deadalive[x+1]+deadalive[totalcells-1]==1)
{
changing[x]=1;
}
else
changing[x]=0;

}
else if(x==totalcells-1)
{

if(deadalive[x-1]+deadalive[0]==1)
{
changing[x]=1;
}
else
changing[x]=0;
}
else
{
if(deadalive[x-1]+deadalive[x+1]==1)
{
changing[x]=1;
}
else
changing[x]=0;
}
}
//make two arrays the sam

Solution

Here is an idea to speed things up, given that the input is only 15 numbers:

  • Since the numbers are binary, you could represent the board as a bitmask in an integer instead of an array (see wikipedia/masks).



  • There are only \$2^{15}\$ possible states. You could create a Map from each state bitmask to the next. Then each iteration in your algorithm is gonna be a simple map lookup.



There are more optimizations you could to make it even faster, but this should be enough.

Context

StackExchange Code Review Q#154022, answer score: 2

Revisions (0)

No revisions yet.