Wireworld/Java: Difference between revisions

m
Use Java 5 highlighting, whitespace, templates
(Moving from main task page to shorten it)
 
m (Use Java 5 highlighting, whitespace, templates)
 
Line 1:
{{works with|Java|1.5+}}
With help from [[Conway's Game of Life#Java]]:
<lang javajava5>public class Wireworld {
public static final char empt = ' ';
public static final char head = 'h';
Line 6 ⟶ 7:
public static final char ctor = '.';
 
public static char[][] iterate(char[][] world) {
char[][] nextGen = new char[world.length][world[0].length];
for (int row = 0; row < world.length; row++) {//each row
String thisRow = new String(world[row]);
for (int col = 0; col < thisRow.length(); col++) {//each char in the row
switch (world[row][col]) {
case head:
Line 26 ⟶ 27:
String same = "";//neighbors in the same row
String below = "";//neighbors below
if (col == 0) {//all the way on the left
//no one above if on the top row
//otherwise grab the neighbors from above
Line 35 ⟶ 36:
//otherwise grab the neighbors from below
below = (row == world.length - 1) ? null : new String(world[row + 1]).substring(col, col + 2);
} else if (col == thisRow.length() - 1) {//right
//no one above if on the top row
//otherwise grab the neighbors from above
Line 44 ⟶ 45:
//otherwise grab the neighbors from below
below = (row == world.length - 1) ? null : new String(world[row + 1]).substring(col - 1, col + 1);
} else {//anywhere else
//no one above if on the top row
//otherwise grab the neighbors from above
Line 55 ⟶ 56:
}
int heads = headsInNeighborhood(above, same, below);
switch (heads) {
case 1:
case 2:
Line 68 ⟶ 69:
}
 
private static int headsInNeighborhood(String above, String same, String below) {
int ans = 0;
if (above != null) {//no one above
for (char x : above.toCharArray()) {//each neighbor from above
if (x == head) {
ans++;//count it if a head is here
}
}
}
for (char x : same.toCharArray()) {//two on either side
if (x == head) {
ans++;//count it if a head is here
}
}
if (below != null) {//no one below
for (char x : below.toCharArray()) {//each neighbor below
if (x == head) {
ans++;//count it if a head is here
}
Line 92 ⟶ 93:
}
 
public static void main(String[] args) {
char[][] world = {
"th.........".toCharArray(),
Line 100 ⟶ 101:
"ht.. ......".toCharArray()
};
for (int i = 0; i <= 20; i++) {
System.out.println("Iteration " + i + ":");
printWorld(world);
Line 108 ⟶ 109:
}
 
private static void printWorld(char[][] world) {
for (char[] row : world) {
System.out.println(row);
}
}
}</lang>
{{out}}
Output:
<pre style="height:30ex;overflow:scroll">Iteration 0:
th.........
Anonymous user