How to generate random numbers without rethinking in Java?

Asked

Viewed 543 times

-1

Something similar to the code below. Numbers in the Random range that do not repeat

public void sorteiaCartelaB() {
        for (int i=0; i < b.length; i++) {
            b[i] = (int)(Math.random() * 60 + 1);
            for (int j=0; j<b.length; j++)
                if (b[i] == b[j] && i != j)
                    b[i] = (int)(Math.random() * 60 + 1);
                else 
                    continue;
        }
        return b;
    }
  • https://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates

2 answers

0

A possibility:

quantidade = ???;
Set<Integer> numeros = new HashSet<>();
Random rnd = new Random(semente);
while (numeros.size() < quantidade) {
    numeros.add(rnd.nextInt(60) + 1);
}

0


Another possibility to implement:

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
class Main {
  private static Scanner scanner;
  public static void main(String[] args) {
    System.out.println("Digite o tamanho da lista");
    scanner = new Scanner(System.in);
    int quantidade = scanner.nextInt();
    List<Integer> listadistintos = new ArrayList<Integer>();
    int sorteio;
    do {
      boolean adicionarLista = true;
      sorteio = (int) (Math.random() * 100);  //ajustar valores aqui
      for (int i : listadistintos){
        if (i == sorteio) {
          adicionarLista = false;
          break;
        }
      }
      if (adicionarLista) { listadistintos.add(sorteio); }
    } while (listadistintos.size() < quantidade);
    //System.out.println("Lista de números distintos");
    //for (int x : listadistintos) {
    //  System.out.println(x);
    //}
  }
}

One thing to be careful about is that depending on the parameters you pass, you can generate an infinite loop.

Ex: If I change the parameters to Math.random() * 5)

And I want to generate a list with 6 positions. The output condition of the loop do will never be achieved.

Because there is only the possibility of being drawn 5 different numbers.

0 , 1 , 2, 3, 4

Browser other questions tagged

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