class T extends Thread
{
private int[][] states;
private int[] ruleStates;
private int source;
private int target;
private int start;
private int end;
public T(int[][] states, int[] ruleStates, int source, int target, int start, int end)
{
this.states = states;
this.ruleStates = ruleStates;
this.source = source;
this.target = target;
this.start = start;
this.end = end;
// Thread starten:
start();
}
public void run()
{
for(int i = start; i < end; ++i)
{
states[target][i] = ruleStates
[
4 * states[source][i - 1] +
2 * states[source][i] +
states[source][i + 1]
];
}
}
}
class Main
{
/**
* Deterministischer Synchroner, 1-dimensionaler Automat ohne Randbehandlung.
* @param int rule 0 bis 255
* @param int count >= 0 Anzahl der Durchläufe
* @param int width > 0 Gitter-Breite
* @return int[]
*/
private static int[] module(int rule, int count, int width) throws InterruptedException
{
// Gitter definieren:
int[][] states = new int[2][width];
// Startzustand:
int target = 0;
states[target][width / 2] = 1; // alles 0, außer in der Mitte eine 1
// rule in Array ablegen:
int[] ruleStates = new int[8];
for(int i = 0; i < 8; ++i)
{
ruleStates[i] = rule % 2;
rule = rule >> 1;
}
// Anzahl Threads:
int p = Runtime.getRuntime().availableProcessors();
int n = Math.min(width - 2, p);
// Anzahl Stati pro Thread:
double threadWidth = ((double)width - 2.0) / (double)n;
// Durchläufe:
for(int i = 0; i < count; ++i)
{
// Bufferzuordnung:
int source = target;
target = (target + 1) % 2;
// zu jedem Prozessor 1 Thread;
int start = 1;
for(int j = 0; j < n; )
{
int end = 1 + (int)Math.round((++j) * threadWidth);
new T(states, ruleStates, source, target, start, end).join();
start = end;
}
}
return states[target];
}
public static void main(String[] args)
{
try
{
int states[] = module(30, 14, 31);
for(int i = 0; i < states.length; ++i)
{
System.out.print(states[i]);
}
}
catch(InterruptedException e)
{
System.out.println("error");
}
}
}