How to generate random matrices without repeating numbers on the same line?

Asked

Viewed 3,097 times

3

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

Type, cannot be: 11 55 55 43 49 30, and yes should be 11 55 52 43 49 30. There should be no repetitions.

I made this code that generates normally, but I 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();
        }
    }
}

3 answers

6

  • Just add a detail: it is using array.. so after generating the list you need to do one lista.toArray()

  • @Pedrolaini is true, but I don’t know if he needs it and should use the array.

  • It is. And I was seeing here: the lista.toArray() returns a Object[ ] and not to convert to int[ ]... then you have to iterate in the list and insert elements 1 to 1 in the array

  • @Pedrolaini anyway he wants the other way.

0

Using this code the numbers do not repeat, as is used the add() and the remove().

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

-1


Just play that code on 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();
}
  • Thanks man. I really wanted it that way.

Browser other questions tagged

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