Java Random Numbers

Asked

Viewed 31 times

0

Hello, I’m trying to do an exercise involving random numbers with the following code:

    int sorteio1 = (int)(Math.random() * 6) +1;
    int sorteio2 = (int)(Math.random() * 6) +1;
    int sorteio3 = (int)(Math.random() * 6) +1;
    int sorteio_usuario = (int)(Math.random() * 6) +1;

However, I am finding the following difficulty: the variables sorteio1, sorteio2, sorteio3, cannot have the same value... Is there any way to do this?

I even thought about taking intervals, for example, the draw goes from 1 to 2, the draw goes from 3 to 4 and the draw goes from 5 to 6. However, I could not find ways to apply this draw by interval in the code above. Maybe using a for each variable draw would work, but I feel like maybe it was a scam...

Is there any way to do that WITHOUT use array, vector, list etc?

  • Hello Victor, can solve easily with "recursiveness". Run the sorteio1, then run the sorteio2 and compare if it is equal to sorteio1, if yes do a recursion to run again, until the value is different (probably in the second attempt it will be already, but an infinite loop solves, it can also be a recursion method). Now run sorteio3 and compare the sorteio1 and sorteio2, with an IF check if 3 is equal to 1 or 2, if it is equal to one of them, make a recursion (can be with loop or a method that calls itself), when it is different close the loop.

  • Still if it is to have a dynamic number of draws use A vector would solve easily private ArrayList<Integer> sorteios = new ArrayList<Integer>();, it would add the results to: for (int i = 1; i <= numSorteios; i++) { sortear.add(sortear()); }, and in the method (no need for a method, but preferred to separate) checks whether the number already exists in sorteios with a simple IF using ArrayList.contains() thus int sortear() { int novo = (int) (Math.random() * 6) + 1; if (sorteios.contains(novo)) { return sortear(); /*se já existir sorteia novamente*/ } else { return novo; } }

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.