简体   繁体   中英

Printing random numbers in a 2D array only once

I'm trying to print a 2D array of random numbers from 1 to 15 only once. I've been able to print out the array but only sequentially.

int x =0;
public void Numberbox(){
            int[][] a2 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,x}};

  String output = "";   // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) 
{
for (int col = 0; col < COLS; col++) 
{
output += " " + a2[row][col];
}
output += "\n";
}
    System.out.print(output);


}

You could use a collection, for example a list, and use the built-in shuffle function. For example:

public static void main(String... args) throws Exception {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 16; i++) {
        list.add(i);
    }
    System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    Collections.shuffle(list);
    System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]

    int[][] a2 = new int[4][4];
    for (int i = 0; i < 4; i++) {
        for (int j = 0;  j< 4; j++) {
            a2[i][j] = list.get(i*4 + j);
        }
    }
    System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14, 2, 4], [15, 13, 12, 8]]
}

我认为您应该出于您的目的使用Collections.shuffle()

Use Random.nextInt() within the inner loop to generate the random numbers:

public class RandomGrid
{
    public static void main(String[] args)
    {
        Random r = new Random();
        int ROWS = 4;
        int COLS = 3;
        String output = ""; // Accumulate text here (should be StringBuilder).
        for (int row = 0; row < ROWS; row++)
        {
            for (int col = 0; col < COLS; col++)
            {
                output += " " + r.nextInt(16);
            }
            output += "\n";
        }
        System.out.print(output);
    }
}

Example output:

 12 9 10
 8 7 3
 8 10 11
 15 14 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM