Home > Programming, Technology > Java Program to construct the Magic Square

Java Program to construct the Magic Square


Do you know what is Magic Square. Read here. Probably you might have played with this.

It is typically a matrix or table in which the sum of the elements of any row is equal to that of sum of the elements of any column and diagonal.

Here is the example of such magic square with dimension three

 

There are different ways to solve this. Here I took one of the easiest ways of solving it. Place the given user specified  input in the middle of the first row from that onwards keep on increasing the user given input by one and find the correct place for inserting that number. One way is find the upper diagonal element to that and place there if you find there is an already existing element then go down to the correct number and place there. If you go out of the square like in 3*3 table if 13 element go down i.e., 23 and place the element there. If you go out of the square beyond the column number then go to the first element like rotating method.

 

Program:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author Vasanth Raja Chittampally
 */
public class MagicBox {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter the dimension of the matrix (Odd dimension only): ");
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        if(n%2!=0) {
        int box[][]=new int[n][n];
        System.out.println("Enter the first element:");
        int firstEle=Integer.parseInt(br.readLine());
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                box[i][j]=0;
            }
        }
        int row=0;
        int col=n/2;
        for (int p = 0; p < n*n; p++) {
                box[row][col]=firstEle;
                firstEle++;
                row--;
                col++;
                if(row==-1)
                   row=n-1;
                if(col==n)
                   col=0;
                if(row==n-1 && col==0)
                {
                    row=1;
                    col=n-1;
                }
              if((box[row][col]!=0)) {
                   row+=2;
                   col--;
                 if(row&gt;n) row=0;
                if(col==-1) col=0;
            }
        }
        System.out.println("Magic Box");
         for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if(box[i][j]/10==0)
                    System.out.print( box[i][j]+"    ");
                else
                    System.out.print( box[i][j]+"   ");
            }
             System.out.println("");
        }
    }
}
}

Sample Input:
7
1
Output:
Magic Box
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20

Here is the same code if you want to try out use this online java compiler.

Advertisements
  1. November 3, 2010 at 7:28 pm

    I am interested in code that will find all examples of 7 x 7 magic square that retains 418 units of water ….

    Note section 13 on website mentioned

    Thanks

  2. darlyn
    November 24, 2010 at 11:50 pm

    tnx to you b-coz i did my activity from your great examples here.

  3. Craig Knecht
    January 9, 2011 at 8:47 pm

    Perhaps the 7×7 magic square enumeration for all examples retaining 418 units of water is finished …. 10,432 proven examples. The 8×8 MS 797 units retained …. only one proven pattern for maximum retention .. . is the next challenge.

    1 26 41 39 50 47 40 16
    36 43 21 61 9 7 51 32
    42 6 62 15 57 25 5 48
    29 58 14 23 27 56 4 49
    52 13 20 33 22 18 64 38
    53 17 35 24 8 60 19 44
    37 63 12 11 59 2 46 30
    10 34 55 54 28 45 31 3

  4. Craig Knecht
    January 9, 2011 at 10:55 pm

    7×7 magic square water retention

    If you have any interest in this topic … I provide the following code for the F1 compiler. The F1 compiler is a free download. The Zimmermann programing contest provided the basic pattern for a 7×7 magic square with maximum retention of 418 units of water. By providing the limited number range allowed for each of the 49 cells + the additional constraints … that the solution must contain > 417 units of water + corner sum restriction to 35 or 36 … the logic constraint process will give all examples for those parameters.

    ////// 10 – 15 – 2010
    ///// F1 compiler logic constraint program
    ///// examination of pattern maximum retention
    ///// 7 x 7 Magic Square

    /////

    /////// e7 = 35 a1 + a7 + g1 + g7 = 36 8351 examples

    ///// 418 units retained ..

    pred Magic5Assoc() iff
    ms::[0..48]->>L[1..49] &
    ms = [ a1, a2, a3, a4, a5, a6, a7,
    b1, b2, b3, b4, b5, b6, b7,
    c1, c2, c3, c4, c5, c6, c7,
    d1, d2, d3, d4, d5, d6, d7,
    e1, e2, e3, e4, e5, e6, e7,
    f1, f2, f3, f4, f5, f6, f7,
    g1, g2, g3, g4, g5, g6, g7 ] &

    a1 + a7 + g1 + g7 35 &

    ////////////

    a1 20 &
    a2 37 &
    a3 37 &
    a4 37 &
    a5 16 &
    a6 10 &
    a7 21 &
    b1 42 &
    b2 2 &
    b3 4 &
    b4 2 &
    b5 42 &
    b6 22 &
    b7 39 &
    c1 14 &
    c2 17 &
    c3 17 &
    c4 23 &
    c5 6 &
    c6 39 &
    c7 21 &
    d1 42 &
    d2 2 &
    d3 15 &
    d4 2 &
    d5 41 &
    d6 22 &
    d7 30 &
    e1 < 35 &

    e2 45 &

    e4 > 5 &
    e4 45 &

    e6 30 &
    f1 6 &
    f2 3 &
    f3 45 &

    f5 > 3 &
    f5 22 &
    f7 13 &
    g1 30 &
    g2 32 &
    g3 28 &
    g4 19 &
    g6 2 &
    g7 417 &

    // need to change above line of code to line below to pick up the 320 solutions
    // where 36 and 35 change position on the square

    //( 456 – ( b3 + b4 + b5 + c2 + c3 + c4 + c5 + c6 + d3 + d4 + d5 + e4)) + ( 93 – ( e2 + f2 + f3

    a1 + b1 + c1 + d1 + e1 + f1 + g1 = 175 &
    a2 + b2 + c2 + d2 + e2 + f2 + g2 = 175 &
    a3 + b3 + c3 + d3 + e3 + f3 + g3 = 175 &
    a4 + b4 + c4 + d4 + e4 + f4 + g4 = 175 &
    a5 + b5 + c5 + d5 + e5 + f5 + g5 = 175 &
    a6 + b6 + c6 + d6 + e6 + f6 + g6 = 175 &
    a7 + b7 + c7 + d7 + e7 + f7 + g7 = 175 &

    a1 + a2 + a3 + a4 + a5 + a6 + a7 = 175 &
    b1 + b2 + b3 + b4 + b5 + b6 + b7 = 175 &
    c1 + c2 + c3 + c4 + c5 + c6 + c7 = 175 &
    d1 + d2 + d3 + d4 + d5 + d6 + d7 = 175 &
    e1 + e2 + e3 + e4 + e5 + e6 + e7 = 175 &
    f1 + f2 + f3 + f4 + f5 + f6 + f7 = 175 &
    g1 + g2 + g3 + g4 + g5 + g6 + g7 = 175 &

    a1 + b2 + c3 + d4 + e5 + f6 + g7 = 175 &
    a7 + b6 + c5 + d4 + e3 + f2 + g1 = 175 &

    PrettyPrintA(ms,0)
    ///////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////
    local proc PrettyPrintA(ms:>L[1..49], i:<I) iff
    if i < 7 then
    j = i*7 &
    Print('\n') &
    PrintDigit(ms(j)) &
    PrintDigit(ms(j+1)) &
    PrintDigit(ms(j+2)) &
    PrintDigit(ms(j+3)) &
    PrintDigit(ms(j+4)) &
    PrintDigit(ms(j+5)) &
    PrintDigit(ms(j+6)) &

    PrettyPrintA(ms,i+1)
    else
    Print('\n')

    end

    local proc PrintDigit(d:<L) iff
    if d < 10 then
    Print(' ',d,' ')
    else
    Print(d,' ')
    end

    5 22 40 39 38 19 12
    25 46 15 11 6 45 27
    42 18 20 21 26 7 41
    24 44 4 17 14 43 29
    32 2 49 9 47 1 35
    31 10 13 48 8 37 28
    16 33 34 30 36 23 3

    ___ Solution: 1 ___ [00:01:39] __ [Backtracks: 2110589] ____

    5 22 40 39 38 19 12
    25 46 13 11 8 45 27
    42 18 20 21 26 7 41
    24 44 4 17 14 43 29
    32 2 49 9 47 1 35
    31 10 15 48 6 37 28
    16 33 34 30 36 23 3

    ___ Solution: 2 ___ [00:01:39] __ [Backtracks: 2110674] ____

    5 22 38 39 40 19 12
    25 46 15 11 4 45 29
    42 18 20 21 26 7 41
    24 44 6 17 14 43 27
    32 2 49 9 47 1 35
    31 10 13 48 8 37 28
    16 33 34 30 36 23 3

    ___ Solution: 3 ___ [00:01:39] __ [Backtracks: 2111613] ____

    5 22 38 39 40 19 12
    25 46 13 11 8 45 27
    42 18 20 21 26 7 41
    24 44 15 17 4 43 28
    32 2 49 9 47 1 35
    31 10 6 48 14 37 29
    16 33 34 30 36 23 3

    ___ Solution: 4 ___ [00:01:39] __ [Backtracks: 2111672] ____

    5 22 38 39 40 19 12
    24 46 13 11 8 45 28
    42 18 20 21 26 7 41
    25 44 15 17 4 43 27
    32 2 49 9 47 1 35
    31 10 6 48 14 37 29
    16 33 34 30 36 23 3

    ___ Solution: 5 ___ [00:01:39] __ [Backtracks: 2111927] ____

    5 22 38 39 40 19 12
    24 46 6 11 14 45 29
    42 18 20 21 26 7 41
    25 44 15 17 4 43 27
    32 2 49 9 47 1 35
    31 10 13 48 8 37 28
    16 33 34 30 36 23 3

    ___ Solution: 6 ___ [00:01:39] __ [Backtracks: 2112033] ____

    5 23 40 39 38 19 11

  5. Ria
    February 11, 2013 at 1:24 pm

    Woah , dude ur a programming genius!!!! Even i’ve jus started doing programs ,, bt how do u do these with such ?!?!?!? U know ur really goog 🙂

  6. Harshita Lanka
    January 12, 2014 at 7:10 am

    if(row>n)

    What’s this?

  1. January 2, 2011 at 1:57 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: