"Assume that each element of this array has three values:
0 - if empty 1 - if it contains a tree 2 - if it contains fire
With probability p given by the user, place a tree at each position of F (use Math.random()
). Choose a tree to fire (change its value to 2).
Apply the following rule until there are no more elements with a value of 2:
- If there is a tree in position (i, j) and there is fire in some neighboring position, change tree to fire.
- If there is fire in a position (i, j) and there is no tree in the vicinity, change fire to empty.
Determine the percentage of trees that survived. "
I dare say I made it work. Here's my code:
package aula10;
import java.util.*;
public class aula10_1 {
public static void main(String[] args) {
int n, i, j;
double p;
Scanner ent = new Scanner(System.in);
ent.useLocale(Locale.US);
System.out.println("Digite a dimensão da matriz (que é quadrada):");
n = ent.nextInt();
System.out.println("Digite a probabilidade de haver uma árvore em qualquer ponto da floresta:");
p = ent.nextDouble();
int [][] F = new int[n][n];
Random rnd = new Random();
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
F[i][j] = rnd.nextInt();
if (F[i][j] < p) {
F[i][j] = 1;
} else {
F[i][j] = 0;
}
System.out.print(F[i][j]+" ");
}
}
int k = rnd.nextInt(n-1);
int l = rnd.nextInt(n-1);
while (true) {
if (F[k][l] == 1) {
F[k][l] = 2;
break;
}
}
System.out.println(Arrays.deepToString(F));
}
}
I tested it several times and went into some infinite looping. With Debug I have been able to identify and fix some errors, but even so sometimes it gives problem with small probabilities. I do not know exactly what happens ... My knowledge in Java is very limited, so I was satisfied with this code. But I still welcome suggestions for improvement.