dimanche 19 mai 2019

Loop for generating 6 non-equal numbers is failling (java)

I have here the following code:

    import java.util.Random;

    public class Main {
        public static void main(String[] args) {
            int numnovo, numeros[], j;
            boolean igual;
            numeros = new int[6];

            Random rand = new Random();

            numnovo = rand.nextInt(60)+1;
            numeros[0] = numnovo;

            System.out.println("Número 1: " + numeros[0]);

            for(int i = 1; i < 6; i++)
            {
                do
                {
                    igual = true;
                    numnovo = rand.nextInt(60)+1;
                    j=0;
                    while(j<=i && igual)
                    {
                        igual = (numnovo == numeros[j++]);
                    }
                }while(igual);
                numeros[i] = numnovo;
                System.out.println("Número " + (i+1) + ": " + numeros[i]);
            }
    }
}

So, here's one of the results I got from it:

numeros[0]=48 
numeros[1]=31
numeros[2]=52
numeros[3]=25 - repeated
numeros[4]=18
numeros[5]=25 - repeated

Yet, while analyzing the code, I'd suppose it would come to the following situation inside of the loop:

i=5

j=0 numeros[0]=48   false
j=1 numeros[1]=31   false
j=2 numeros[2]=52   false
**j=3   numeros[3]=25   true**

Specifically in the marked line, I'd suppose the condition for the while loop (j<=i && igual) to be satisfied and, therefore, it would exit the loop and generate a new number, but that didn't happen, it went straight through and considered it a valid value.

I've cracking my head open around this problem for a day or so already and can't seen to find a solution, and it is something that happens in about 10% of all execution, so it wasn't an isolated case.

I tried to look into the "j vs i" relation as in "Is the repeated number always close to the previous one" but in some executions the repeated number would be the numeros[0] and numeros[5], and in others it could be like the numeros[0] and numeros[1], so the thesis didn't work.

I also tried to change condition from && to ||, but got didn't change it even a bit.

I tried also a few different condition sintaxes, as going in the opposite direction (using false statements instead of true), and also different loops instead of Do-While, and still no luck.

So... any help here?




Aucun commentaire:

Enregistrer un commentaire