How to generate random arrays without repeated numbers on the same line?

3

I want to store random numbers from 1 to 60 in an array. When there are equal numbers in the rows, it is to generate another random number.

Type, can not be: 11 55 55 43 49 30, but should be 11 55 52 43 49 30. There should be no repetitions.

I made this code that generates normally, but wanted to remove the repeated numbers from the lines and put new numbers that are not equal.

package Tentativa;
import java.util.Random;
public class Loteria {

    public static void main(String[] args) {
        int[][]mega = new int[7][6];
        int[][]numero = new int[7][6];
        Random gerador = new Random();
        for(int x=0; x<7; x++) {
            for(int y=0; y<6; y++) {
                mega[x][y] = gerador.nextInt(60) + 1;
            }   
        }
        for(int x=0; x<7; x++) {
            for(int y=0; y<6; y++) {
                System.out.print(mega[x][y] + " ");
            }
            System.out.println();
        }
    }
}
    
asked by anonymous 27.08.2015 / 06:35

3 answers

1

Only play this code in main :

int[][]mega = new int[7][6];
Random gerador = new Random();
for(int x=0; x<7; x++) {
    for(int y=0; y<6; y++) {
        int n = gerador.nextInt(60) + 1;
        int z = 0;
        while(z < 6){
            if(mega[x][z] == n){
                n = gerador.nextInt(60) + 1;    
                z = 0;
            }
            z++;
        }
        mega[x][y] = n;
    }   
}
for(int x=0; x<7; x++) {
    for(int y=0; y<6; y++) {
        System.out.print(mega[x][y] + " ");
    }
    System.out.println();
}
    
27.08.2015 / 09:29
6

Generate a list with all possible numbers, shuffle them and get the first 6:

List<Integer> lista = new ArrayList<>(60);
for (int i = 1; i <= 60; i++) {
    lista.add(i);
}
Collections.shuffle(lista);
lista = lista.subList(0, 6);

See working on ideone .

This algorithm is the Fisher-Yates

    
27.08.2015 / 09:42
0

Using this code, the numbers are not repeated, since add() and remove() are used.

Follow the code:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class Gerador {

    public static void main(String[] args) {


            Random rdn = new Random();
            List<Integer> numeros = new ArrayList<Integer>();
            for (int i = 0; i < 10; i++)
                numeros.add(i);
            String b = "";
            for (int i = 0; i < 10; i++) {
                b += numeros.remove(rdn.nextInt(numeros.size()));
            }
            System.out.println(b);
    
15.05.2017 / 04:02