How to generate random numbers in Java without repetition?

Asked

Viewed 108 times

0

I wonder how to generate random numbers without repetition I’m trying this method but it seems to me not working properly.

public static ArrayList<Integer> numerosAleatorios(int inicio, int fim, int quant)
    {

        // cria um objeto da classe Random
        Random rnd = new Random();

        // vamos preencher um ArrayList com a faixa de números
        ArrayList numeros = new ArrayList();
        for (int i = inicio; i < fim; i++)
        {
            numeros.add(i);
        }

        // vamos embaralhar o ArrayList
        for (int i = 0; i < numeros.size(); i++)
        {
            int a = rnd.nextInt(numeros.size());

           Object temp = numeros.get(i);
            numeros.set(i,numeros.get(a));
            numeros.set(a,temp);
        }

        // vamos obter as quantidade de
        // que queremos
        return (ArrayList<Integer>) numeros.subList(0, quant);
    } 
  • You also have this: http://answall.com/q/39951/101

  • 1

    @bigown your answer solved my problem http://answall.com/questions/82819/como-gerar-matrizes-aleat%C3%B3rias-sem-n%C3%Bameros-repeated-in-the-same-line

No answers

Browser other questions tagged

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