1

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 square. The way I am doing it now fills the array in order from 1 to nn 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;
     }
Kat
  • 678
  • 2
  • 11
  • 23

4 Answers4

3

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
  • 398,270
  • 210
  • 566
  • 880
  • 1
    Collections.shuffle will help you accomplish this feat in a simple way. – Luke Magill Mar 23 '10 at 00:50
  • 1
    @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 Mar 23 '10 at 00:55
2

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
  • 8,637
  • 4
  • 30
  • 38
0

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
  • 616,129
  • 168
  • 910
  • 942
0

You can try something like this:

int matrix[][] = new int[8][8];

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix.length; column++) {
        //            for (int row []: matrix){
        //            for (int column : row){

        matrix[row][column] = ran.nextInt(2) ;

        System.out.print(matrix [row][column] + " ");
    }
    System.out.println();
}
helvete
  • 2,455
  • 13
  • 33
  • 37