Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,550,400 members, 5,877,079 topics. Date: Friday, 25 September 2020 at 01:30 AM

Java Programming: Magic Square - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Java Programming: Magic Square (5587 Views)

Is Java Programming Harder Than Microsoft.net Programming / Java Programming Vs Networking: Which Is More Profitable In Nigeria? / Java Programming For Dummies (2) (3) (4)

(1) (Reply) (Go Down)

Java Programming: Magic Square by naijaswag1: 10:57am On May 20, 2011
Magic Square

A magic square is an array of integers such that the sum of every row,the sum of every column, and the sum of each of the diagonal are all equal.

Construction of Magic Square.

There is yet no known straightforward method for construction of even numbered magic squares,the following rule only work for odd numbered squares.

Locate the middle of the top row -the column position at the middle of the top row.Place 1 at this position.Write down successive integers -2,3, along a diagonal going upwards and to the right.When you reach the toprow(as you do immediately since 1 is in the row),continue to the bottom row as though the bottom row were immediately above the top row.When you reach the rightmost column,continue to the leftmost column as though it were immediately to the right of the rightmost one.When you reach the position that is already occuppied,instead drop straight down one position from the previous number to insert the new one.Note that you should drop down one row immediately after you have reached a number that is divisible by the size of the magic square.


I came accross the magic square problem in a QBasic text,the solution wasnt there and I decided to implememnt one in java.I thought it was a simple task but I didnt realized that it would involve a great deal of algorithmic programming and brain racking although not too much like what boys are doing at gcj currently.Someone else could have a shorter and better solution but for those who are quite sure that they are still below or at some basic level in java programming level,you will learn from this.The following programming basic (some of them are supported only in java) featured mostly

*two-dimensional array.
*post and pre increment and decrement and modulus operators
*Use of for loop and use of continue keyword to continue the loop when necessary.
*extensive use of if's control statements.
*static methods



Here are the codes with comments.

public class MagicSquareSolver {


public static int[][] SolveMagicSquare(int n){

int[][] a = new int[n][n];

//the middle of the first row
int middleEarth = (a.length-1)/2;

//various parameters
int count = 1;
int lastrow = a.length-1,toprow = 0,crow = toprow,ccol=middleEarth;

//resolve the first position which is middle of the first row
a[crow][ccol] = count;


//lets start a loop to fill the remaining positions according to the rules

for(int k=2;k<=(n*n);k++){


if(count%n == 0){
crow = ++crow;
a[crow][ccol] = ++count;
continue;
}



if(crow == toprow){

if(ccol < (a.length-1)){
ccol= ++ccol;

//this single movement to the last row frustrated me for 2 hours
crow = lastrow;
a[crow][ccol] = ++count;
continue;

}else if((ccol+1) > (a.length-1)){
crow = ++crow;
a[crow][ccol] = ++count;
continue;
}


}else if(crow != toprow){
ccol = ++ccol;
if(ccol <= (a.length-1)){
crow = --crow;
if(a[crow][ccol] ==0){
a[crow][ccol] = ++count;
continue;
}else if(a[crow][ccol] !=0){
ccol = --ccol;
crow = crow++;
crow = crow++;
a[crow][ccol] = ++count;
continue;
}
}else if(ccol > (a.length-1)){
ccol = 0;
crow = --crow;
a[crow][ccol] = ++count;
continue;
}
}
} return a;
}

// try printing the square elegantly but I noticed that for numbers higher than 19 the table starts to spool over.
public static void printMagicSquare(int[][] b){
int counter=0;
int len = b.length;

if((b.length < 0) & (b.length % 2 == 0)){
return;
}else{

for(int k=0;k<b.length;k++){
System.out.print("----"wink;
}
System.out.print("\n"wink;


for(int g =0;g<b.length;g++){
System.out.print("|"wink;


for(int h=0;h<b[g].length;h++){
if(b[g][h] < 10)
System.out.print(b[g][h] + " "wink;
else if(b[g][h] < 99)
System.out.print(b[g][h] + " "wink;
else if(b[g][h] < 999)
System.out.print(b[g][h] + ""wink;

System.out.print("|"wink;


}

System.out.print("\n"wink;

for(int k=0;k<b.length;k++)
System.out.print("----"wink;

System.out.print("\n"wink;

}


}
}


}

A driver class to test out the efforts.Make sure to run it with the arguments via the IDE or CLI preferrable.

public class MagicSquare{

public static void main(String[] args){
int[][] a = MagicSquareSolver.SolveMagicSquare(Integer.parseInt(args[0]));

MagicSquareSolver.printMagicSquare(a);

}


}
Re: Java Programming: Magic Square by Seun(m): 11:50am On May 20, 2011
Ol boy, why not practice with real problems?
Re: Java Programming: Magic Square by naijaswag1: 12:38pm On May 20, 2011
@Seun

Permit me to call you The Boss.Let me tell you why I am interested in this kind of thing.I started programmer last year and I have been making progress.I have know about Google codejam even when I was not a programmer.The kind of problems featured there are just like this one,probably next year I hope to sign on so i have to do this kind of things everyday together to get the brain working faster also coupled with real application developments to put food on the table so i can break even like you.wish me luck.
Re: Java Programming: Magic Square by Seun(m): 1:59pm On May 20, 2011
Good luck man. It's a good way to get hired by companies like Google.
Re: Java Programming: Magic Square by naijaswag1: 3:02pm On May 20, 2011
The Boss,thanks.This time last year,I was so confused.I just started java and everything was like OMG.Its now that my brains are coming together to get things done.I remember seeking for help and you also replied the post.21 gun salute for you in bits and hex and bytecode.
Re: Java Programming: Magic Square by SayoMarvel(m): 7:38am On May 21, 2011
If you want to really get prepared for codejam, compete on topcoder.com regularly. You'll be surprised. Most times I compete, I'm usually the only Nigeria in the middle of over a thousand programmers around the world.
Re: Java Programming: Magic Square by naijaswag1: 10:47am On May 21, 2011
SayoMarvel:

If you want to really get prepared for codejam, compete on topcoder.com regularly. You'll be surprised. Most times I compete, I'm usually the only Nigeria in the middle of over a thousand programmers around the world.

Did you try the Codejam Africa early this year,at then,I couldnt tell my left from my right very well.I will get on topcoder probably next month.Its a year long preparation which will involve a lot of algorithmic programming,bit manipulation,efficient use of data structures and things like that.I hope to crack all the problems currently on codejam website in the next 3 months.I have done a few simple ones.As for being the only Nigerian,its a usual scenrio but I think that has to change.Lets keep at it and make it happen.
Re: Java Programming: Magic Square by SayoMarvel(m): 3:36am On May 22, 2011
Also, Facebook puzzles is something worth checking out. Its just like CodeJam and the rest. just search for "Computer"on Facebook and "like" it. Then go to the page and click the "Puzzles" tab. Bingo!
Re: Java Programming: Magic Square by naijaswag1: 9:40am On May 23, 2011
Ok I have checked it out.Lets get on with it.
Re: Java Programming: Magic Square by SayoMarvel(m): 9:45am On May 23, 2011
Have you been able to submit the HoppityHop solution. Let me know when you are able to do so. Me email. marvelindaclub <at> <our darling yahoo> dot kom
Re: Java Programming: Magic Square by naijaswag1: 10:09am On May 23, 2011
are u the sayo virus on facebook?
Re: Java Programming: Magic Square by SayoMarvel(m): 3:37pm On May 23, 2011
How did you find me out? You must be a genius! Lets go do our thingy!
Re: Java Programming: Magic Square by naijaswag1: 7:21pm On May 24, 2011
If we meet on FB we will talk,I have seen the hoppity puzzle.that one is just an appetizer.

(1) (Reply)

Shoplog V2.3 (Inclusion of license fee) / English Language Programming Challenge / Programming Tutorials (100% Free)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2020 Oluwaseun Osewa. All rights reserved. See How To Advertise. 93
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.