How to Generate random numbers without repetition in Random? [duplicate]

0

So far I have been able to generate the random numbers and store them, but I have no idea how not to generate repetition.

So far, it looks like this:

package curso1;

import java.util.Random;

public class Curso7 {

public static void main(String[] args) {

//Verificação
boolean jaexiste;

//Vetor 
int[] numeros = new int[5];

//Gerar 5 numeros Aleatórios
Random radom  = new Random();
        int numeroTmp = 0;
        for(int i=0;i<5; i++) {
            numeroTmp=radom.nextInt(20);
            System.out.println(">"+numeroTmp);
        }
}

}
    
asked by anonymous 04.05.2018 / 05:53

3 answers

1

Below is an example commented out. I did based on your code, however you could replace Integer[] with List<Integer> and adapt your code. It's very easy and if you want I can put it later.

Common Example:

import java.util.Random;
import java.util.Arrays;
import java.util.ArrayList;

public class Curso7 {

    public static void main(String[] args) {

        //Vetor
        Integer[] numeros = new Integer[50];

        //Gerar 5 numeros Aleatórios
        Random radom  = new Random();

        for(int i=0;i<50; i++) {
            int numeroTmp = radom.nextInt(20);

            /**
             * Transforma o array Integer para ArrayList e 
             * utilzia o método contains para verificar
             * se o valor já existe
             */
            boolean contains = Arrays.asList(numeros).contains(numeroTmp);

            /* Caso exista informa ao usuáiro */
            if (contains) {
                System.out.println(numeroTmp+" repetido");
            }
            /**
             * Caso não exista adiciona o valor na variável
             * indicada e exibe o valor para o usuário
             */
            else {
                numeros[i] = numeroTmp;
                System.out.println(">"+numeroTmp);
            }
        }
    }
}

Demo: link

Example with Java 8:

import java.util.Random;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.stream.IntStream;

public class Curso7 {

    public static void main(String[] args) {

        //Vetor 
        int[] numeros = new int[50];

        //Gerar 5 numeros Aleatórios
        Random radom  = new Random();

        for(int i=0;i<50; i++) {
            int numeroTmp = radom.nextInt(20);

            /**
             * Utiliza a classe IntStream para verificar os 
             * valores através de uma expressão lambda
             *
             * Essa função irá funcionar semelhante ao forEach.
             */
            boolean contains = IntStream.of(numeros).anyMatch(x -> x == numeroTmp);

            /* Caso exista informa ao usuáiro */
            if (contains) {
                System.out.println(numeroTmp+" repetido");
            }
            /**
             * Caso não exista adiciona o valor na variável
             * indicada e exibe o valor para o usuário
             */
            else {
                numeros[i] = numeroTmp;
                System.out.println(">"+numeroTmp);
            }
        }
    }
}

Demo: link

    
04.05.2018 / 06:37
1

Directly by class Random is not possible.

What you can do is use the data structure Set , which has as characteristics the non-repetition of values and does not maintain any order of the values inserted in it.

In this way, you can only add values in Set without worrying about checking to see if it already exists or not:

public static void main(String[] args) {

    Random random = new Random();
    Set<Integer> numeros = new HashSet<>();

    for(int i = 0; i < 5; i++) {
        numeros.add(random.nextInt());
    }

}

Here we used the implementation HashSet , which has by its definition save the values by their hash codes . Of course, to work as expected, the type you're going to need to override the method hashCode of class Object . In this case, since we are typing our Set with Integer , we do not have to worry, because the Integer class already overrides this method, so it's "just use".

To learn more, worth the reading about the Data structure Set.

    
04.05.2018 / 14:00
0

A simpler solution would be to use a collection called Set. But why a set? Because the main feature of it is not to accept repeated numbers. This means that when the nextInt() method generates a number that already exists in your list, it automatically will not be added. Set itself handles the logic of checking repeated numbers.

Here is the code:

public static void main(String[] args) {

        Set<Integer> numeros = new HashSet<>();

        Random random = new Random();
        for (int i = 0; i < 50; i++) {
            int n = random.nextInt(200);
            numeros.add(n);
        }

        //Como você criou um array de Integer, adicionei esta linha
        //abaixo para converter o Set em um array de Integer, mas
        //ela só é necessária caso você precise que a lista final
        //seja um array.

        Integer[] resultado = numeros.toArray(new Integer[numeros.size()]);

        //Imprimimos os valores usando um método bem bacana de uma 
        //classe chamada Arrays
        System.out.println(Arrays.toString(resultado));

        //Rodando uma vez esse código, obtive:
        //[128, 64, 164, 36, 39, 41, 138, 171, 111, 19, 117, 183, 59]

}

    
04.05.2018 / 14:13