aintno12u
aintno12u

Reputation: 401

random number ranges from 1-8 with a desired output of 1,1,2,2,4,4,3,3,5,5,6,6,7,7,8,8?

i have this problem on how to generate a random number with a range of 1 - 8, i only needed 2 pairs of these number not 1,1,1 or 3,3,3. here are my codes i already imported java.util.random:

          int[][] displayArray = new int[4][4];
        int[][] fieldArray = new int[4][4];

        //generates random Values where "i" represents rows and "j" represents columns
        for (int i = 0; i < fieldArray.length; i++) {
            for (int j = 0; j < fieldArray.length; j++) {
                fieldArray[i][j] = (int) (Math.random() * 8); //generates table with randomized numbers.
            }
        }

        //Print the values
        for (int i = 0; i < fieldArray.length; i++) {          
            for (int j = 0; j < fieldArray.length; j++) {
                 System.out.print("[" + fieldArray[i][j] + "]" + "\t");                     
                }
       // Every time we finish printing a row we jump to the next line.
            System.out.print("\n");
            }

  }

Upvotes: 0

Views: 227

Answers (2)

Peter Walser
Peter Walser

Reputation: 15706

You don't want to have random numbers, but rather a random order of your numbers. Collections.shuffle() offers a method do do that (randomize order in a List).

This code works with any quad size (>0), creating a quadradic array filled with numbers, beginning with 1, containing each number twice, if possible (for odd quad sizes you get an odd amount of numbers):

    int quadSize = 4; //4x4 = 16 tiles, containing the numbers 1-8 twice

    List<Integer> values = new ArrayList<>(quadSize * quadSize);

    // add  number twice (1,1,2,2, ....)
    int num = 0;
    boolean first = false;
    while (values.size() < quadSize * quadSize) {
        if (!first) {
            num++;
        }
        values.add(num);
        first = !first;
    }

    // Shuffle the values (random order)
    Collections.shuffle(values);

    // fill into two-dimensional array
    int[][] fieldArray = new int[quadSize][quadSize];
    int index = 0;
    for (int value : values) {
        fieldArray[index / quadSize][index % quadSize] = value;
        index++;
    }

Output using your print method:

[5] [7] [1] [6] 
[2] [3] [8] [3] 
[6] [8] [5] [1] 
[4] [2] [7] [4] 

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201477

This

for (int j = 0; j < fieldArray.length; j++) {

should be

for (int j = 0; j < fieldArray[i].length; j++) {

in both places. Also, I would prefer

Random rand = new Random();
int val = rand.nextInt(8) + 1; // <-- a random number between 1 and 8.

but with Math.random() you would also need to add + 1 because you'll include 0 (and exclude 8),

fieldArray[i][j] = 1 + (int) (Math.random() * 8);

Upvotes: 3

Related Questions