How do I randomly fill an array in Java?

前端 未结 3 1176
温柔的废话
温柔的废话 2020-12-22 04:24

I\'m writing a program that creates a 2D array from a integer n. I then have to fill the array with values from 1 to the nn array size and check to see if it is a magic

3条回答
  •  猫巷女王i
    2020-12-22 04:48

    To create a random square matrix of values from 0 to n*n-1:

    System.out.print("Enter an whole number: ");
    int n = scan.nextInt();
    int size = n * n;
    
    // create see dvalues
    List values = new ArrayList(size);
    for (int i=0; i

    It's only a slight modification to use the range 1 to n*n.

    The first stage seeds the range with unique values then uses the standard function Collections.shuffle() to randomize the order.

提交回复
热议问题