How do I avoid infinite loopings in an array?

2

"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.

    
asked by anonymous 19.11.2014 / 20:25

1 answer

1

Given a i,j position in the forest, the neighbors of this position are:

F[i-1][j-1]
F[i-1][j]
F[i-1][j+1]
F[i][j-1]
F[i][j+1]
F[i+1][j-1]
F[i+1][j]
F[i+1][j+1]

For every position you walk in the forest, that is, for every% of_with_% within the% internal_with%%, you have to check each of the neighbors for the conditions proposed in the problem (taking the be careful not to check outside the forest area, ie limiting to (i,j) , for , for j and i-1 >=0 ).

You should repeat these j-1 >= 0 and i+1 < n while there is a tree catching fire.

    
19.11.2014 / 20:35