Generate a random two-dimensional array of non-repeating numbers Java

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

The user will type in the number for i (variant), then the number for j (elements for every variant), and finally the maximum value possible (maxElem). Using the inputed values, the task is to generate nonrepeating random numbers ( nonrepeating in a variant, meaning for i , but the numbers may repeat during the entire array).

For example, a successful output giving the input 3 (i), 5 (j), 9 (maxElem) , would be:

  4   |8|1|7|9

3|8|2| 4 |5

2|6| 4 |8|5

As you may notice, the number 4 repeats itself during the entire array for 3 times (allowable). But, for i=0 , number 4 is unique.

Please, guide me what would be the changes to this code:

static Scanner sc = new Scanner(System.in);

static int maxElem;

public static void main(String[] args) {

    int[][] greatLoto;

    System.out.println("Of how many variants will the ticket consist?  ");
    int variants = sc.nextInt();

    System.out.println("Of how many elements will the variants consist? ");
    int elements = sc.nextInt();

    System.out.println("Which value should be considered the maximum value? ");
    maxElem = sc.nextInt() + 1;

    greatLoto = new int[variants][elements];

    System.out.println("Initial values: ");
    show(greatLoto);

    System.out.println("Modifying values...");
    modified(greatLoto);

    System.out.println("Newest values: ");
    show(greatLoto);

}

private static void show(int[][] greatLoto) {
    for (int i = 0; i < greatLoto.length; i++) {
        for (int j = 0; j < greatLoto[i].length; j++) {
            System.out.print("|" + greatLoto[i][j] + "|");
        }
        System.out.println("");
    }
    System.out.println("");
}

private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
    for (int i = 0; i < greatLoto.length; i++) {
        for (int j = 0; j < greatLoto[i].length; j++) {

            while (Arrays.asList(greatLoto[i]).contains(r)) {
               r = new Random(System.currentTimeMillis());
            }
            greatLoto[i][j] = r.nextInt(maxElem);;

        }
        System.out.println("");

    }

}

Answers

This is more of a comment but too long: don t use random.next() because it forces you to check for uniqueness. Instead fill a list with the valid values and shuffle it:

List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);

Then you can simply iterate over the values and take the j first numbers.

Note that if j is significantly greater than i using the random approach would probably be more efficient.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/26033962/generate-a-random-two-dimensional-array-of-non-repeating-numbers-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils