How to Generate random numbers without repeating in Random?

Asked

Viewed 3,989 times

0

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

So far it’s been 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);
        }
}

}
  • Add values to a variable of type List and check every new catch.

  • Could you exemplify? I’m a beginner

  • I voted to reopen because the solution that the linked question answer cites is not the desired solution. It wants random numbers generated by the class Random and not by numbers stored in a list.

3 answers

1

Below is a commented example. I did it based on your code, but you could replace it Integer[] for List<Integer> and adapt your code. It is very easy and if you want I can put 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);
            }
        }
    }
}

Demonstration: http://tpcg.io/0zM13d

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);
            }
        }
    }
}

Demonstration: http://tpcg.io/YjFasr

  • Vlw guys, I got it done using Boolean .

1

Directly by the class Random is not possible.

What you can do is use the data structure Set, which has the characteristics of not repeating values and not maintaining any order of the values inserted in it.

That way, you can just add the values in Set without worrying about checking whether 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 was used the implementation HashSet, which has as its definition to keep the values by their respective hash codes. Obviously, in order for it to work as expected, the type you will store needs to override the method hashCode class Object.
In that case, how are we typing our Set with Integer, we don’t need to worry, because the class Integer already override this method, so it’s "just use".


To learn more, is worth the reading on the data structure Set.

0

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

Here’s 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]

}

Browser other questions tagged

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