Abwatts
Abwatts

Reputation: 31

Magic Square program help in Java

This is homework that we got in my Computer Science class dealing with 2D Arrays. I tried understanding the code, but unfortunately, I'm having a hard time understanding some of the code. This is the code that we were provided with:

public class Magic {
    public static void main(String[] args) {

        // Initializing a variable named n and assigning the integer 3 to it
        int n = 3;
        // Initializing a multi-dimensional array with 3 rows and 3 columns max
        int m[][] = new int[n][n]; // 3 by 3

        int i, j;
        // Assigning 1 to variable num
        int num = 1;

        int nn = n * 3 / 2; //4


        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++; 

                System.out.println(num);
            } // next j
        } //next i

        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) {
                System.out.print(m[i][j] + "\t");
            } // next j
            System.out.println();
        } //next i
    } //end main()
} //end class Magic

Now my problem is that I don't understand this snippet of code specifically:

for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++;
    } 
}

What does this line of code do in the loop? I'm not sure why the modulus is also used in this line. Is it there to limit the range of the generated numbers?

m[(j - i + nn) % n][(i * 2 - j + n) % n] = num++;

Upvotes: -2

Views: 1393

Answers (2)

Derek Plautz
Derek Plautz

Reputation: 108

m, the "multi-dimensional" array (really just an array of arrays), has size n by n, therefore the max indices into the array are n-1 and n-1 (because indexing starts at 0).

A clever way to safely achieve indexing into m is by using the modulo operator %. You can think of the result of a % b as the "remainder" when you divide a / b (read more on Java's modulus operator here).

When you perform a % b where a >= 0 and b > 0, the result will always be strictly less than b. Therefore in our case, the modulus is used to index into m with a number that is strictly less than n (which is what we want or else we'd get some out of bounds exception!)

Upvotes: 1

fafl
fafl

Reputation: 7385

You can get an idea by looking at the generated magic square, it looks like this:

8   3   4   
1   5   9   
6   7   2

The first coordinates (where i=0 and j=0) are 4%3=1 and 3%3=0. For the next coordinate, j increases by one and makes the coordinate go one left and one down. The modulus operator makes sure that the coordinates stay inside the square. After j has been incremented three times, i gets incremented and j gets reset to 0, so that every third move is straight to the right. After nine moves, the square is full.

Upvotes: 1

Related Questions