views:

222

answers:

3

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 n*n array size and check to see if it is a magic square. The way I am doing it now fills the array in order from 1 to n*n array size. How can I make that random?

My code:

System.out.print("Enter an whole number: ");
     int n = scan.nextInt();

     int [][] magic = new int [n][n];

     for (int row = 0; row < magic.length; row++)
     {
        for(int col = 0; col < magic[row].length; col++)
            magic[row][col] = ((row * n) + 1) + col;
     }
+3  A: 

You'll need to shuffle the values. You could shuffle each row, then each column, but I suggest you put all the values in one big n * n 1D array and shuffle that, then fill the 2D array.

Bill the Lizard
Collections.shuffle will help you accomplish this feat in a simple way.
Luke Magill
@Luke: That's probably how I would do it. There's only a tiny amount of overhead in using a Collection of Integer objects over an array of int values, so it's definitely worth it. On the other hand, everyone should implement a proper shuffling algorithm once in their lives just for educational purposes. :)
Bill the Lizard
@bill, agreed! :)
ultrajohn
A: 

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

 List<Integer> numbers = new ArrayList<Integer>();
 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++);
 }
objects
A: 

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<Integer> values = new ArrayList<Integer>(size);
for (int i=0; i<size; i++) {
  values.add(i);
}
Collections.shuffle(values);

// now create the magic square
int[][] magic = new int[n][];
int index = 0;
for (int i=0; i<n; i++) {
  magic[i] = new int[n];
  for (int j=0; j<n; j++) {
    values.get(index++);
  }
}

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.

cletus