How do I randomly fill an array in Java?

前端 未结 3 1170
温柔的废话
温柔的废话 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条回答
  •  春和景丽
    2020-12-22 05:02

    create a shuffled list of numbers to add to your array, something like this:

     List numbers = new ArrayList();
     for (int i=1; i<=n*n; i++) numbers.add(i);
     Collections.shuffle(numbers);
    
     int [][] magic = new int [n][n];
    
     int index = 0;
     for (int row = 0; row < magic.length; row++)
     {
        for(int col = 0; col < magic[row].length; col++)
            magic[row][col] = numbers.get(index++);
     }
    

提交回复
热议问题