## 17 Sep Recall that a magic square is a 2-dimensional square array with n rows and n columns where each row, col, and diagonal add up to the same value. The value that every row, column, and

Recall that a magic square is a 2-dimensional square array with n rows and n columns where each row,

col, and diagonal add up to the same value. The value that every row, column, and diagonal adds up to is

called the magic sum. For example, here is a magic square for the case n = 4 with a magic sum of 34:

6 10 7 11 3 8 9 14 12 1 16 5 13 15 2 4

If a size n magic square contains all of the number from 1 to n2 exactly once (as in the example above) we

call this a standard magic square and it is not hard to show that the magic sum of a standard size n magic

square is n×(n2 +1)

2 .

You are to write a program that will find standard magic squares in three different ways, by

implementing the following 3 algorithms.

Purely random. Randomly put the numbers from 1 to n2 into an n × n array and then check to see if it is

a magic square. Fill the array from top to bottom, left to right order. In other words, first fill the first row

from left to right, then the second row, etc. Do this repeated until either a magic square is found or some

limit for the number of tries is reached. The limit will be a parameter to your magic square method.

The hardest part of implementing this is finding an efficient way to it. For example, in the 4 × 4 case,

how do we get the numbers from 1 to 16 randomly into the array? The way I did it was to create a 16

element array (in general you will create a n × n array) and put the numbers from 1 to 16 into that array. I

then randomly found one of the 16 elements, put it into the magic square array, and switched that element to

the end of the array so that I would never use it again. For the next step I randomly selected an element from

the first 15 spots in the array, put that in the magic sum array, and then swapped it so that it is 1 from the end

of the array.

Here’s how the example above got started. Let’s call my 16-element array num. It starts looking like this:

num: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

The algorithm found a random location in the 16-element array, in this case it’s location 5 with value 6, put

the 6 in the first position of the magic square and then swapped that 6 with 16 at the end of the num array,

giving us:

num: 1 2 3 4 5 16 7 8 9 10 11 12 13 14 15 6

Next the algorithm found a random location in the first 15 spots of num, in this case it was 10 which was

then put into the magic square and moved to the right of num giving us:

num: 1 2 3 4 5 16 7 8 9 15 11 12 13 14 10 6

Continue this until the entire magic square array is filled.

If you have an alternative way for doing this bring it up in a Discussion.

For finding random numbers you can either use Math.random or the Random class. Look these up in the

Java docs here and here. I think the Random class is easier to use but just be sure not to instantiate too many

Random objects. You only need 1.

Last element of each row not random. This algorithm is the same as the purely random algorithm

except when placing an element at the end of the row do not choose randomly but select the only element

that works based on the magic sum. Looking at the 4 × 4 example above, the algorithm would have chosen

6, 10, and 7 randomly but now the only number that will work for the last spot is 11, so simply place that

number in that spot in the array. The implementation of this is going to be similar to the purely random one,

but you will need some addition code or methods to find the number for that last spot of each row. Don’t

forget that it might not always be possible to find that last value. For example, suppose the first 3 random

values put in the magic square array are 2, 3, and 5. Since the magic sum of a 4 × 4 array is 34 we would

need the value 24, but the largest number available is 16.

You should notice that this algorithm finds solutions much faster than the purely random one. In fact, my

purely random program only found solutions to n = 3 cases in a reasonable amount of time. n = 4 would

frequently take more than 100,000,000 tries. But n = 4 works well with this algorithm, finding solutions

quite quickly. The average number of tries necessary for this algorithm to find a magic square is just a little

over 5,000,000.

Pair heuristic. This only works for cases where n is even and I will describe it for the n = 4 case. Recall

that the magic sum for an n = 4 array is 34. Put elements randomly into the rows in pairs where each pair

sums to 17, ½ the magic sum value. For example, here is a magic square found using that algorithm.

1 12 5 16 15 9 8 2 14 6 11 3 4 7 10 13

In this case the first random value found was 5. It was randomly placed in the first row. Notice this is

different from how the other two algorithms work. 12 is the value that pairs with 5 to get to 17 so we place

12 randomly in one of the remaining open positions. The next random number found was 1 and it was placed

randomly in one of the remaining positions and then its pair, 16, was placed in the only remaining spot in the

first row.

This algorithm performs considerably better than the previous algorithm, requiring on average of only

about 600,000 tries to find a solution.

I look forward to your thoughts about other general algorithms that will allow us to find magic squares

for even larger n’s.

Below is an outline of the class and the methods that need to be implemented for that class. Do not make

any changes to the classes, variables, names, etc. Just add code. Questions? Start or continue a Discussion.

This assignment is as much about following instructions as it is about programming. Be sure your

methods do exactly what is expected of them and all rules mentioned below and in Canvas and class

discussions are followed.

What follows are general rules that you must follow for this and, as applicable, all other programs you

write in this class. Failure to follow these rules will cost you points.

1. I will eventually post a final test program. A sample test program is already posted to help get you

started. Don’t wait for my final test program to appear to start debugging your program. You should

begin testing with your own test programs. Also, the final test program I post may not be the same test

program I run on your programs. You cannot assume your program is correct just because it works on the

posted test program.

2. Submit your program through Canvas with the name prog1.java. Be sure that my main (test) program is

in a different file from your class(es) and you should not submit my test program. Also, do not make your

classes "public". If you deviate from any of these rules you will lose points because doing so makes it

much more difficult for me to manage and test your programs.

3. The top of your prog1.java file (and all java code that you turn in to me in the future) should begin with

comments that show: (i) Your name; (ii) Comp 282 and clear mention of what time your class meets; (iii)

The assignment number; (iv) The date the assignment was handed in (which is not necessarily the same

as the due date); (v) A brief description of what is contained in the file.

4. For all Java code you turn in:

a) Choose clear and suggestive variable names.

b) Be sure lines do not wrap to the first column of the next line or disappear off the end of the page.

c) Use comments generously to describe how your methods work. Comments should appear

inside your methods, too – not just at the top. That said, don't overdo the comments.

d) There should be no more than one return statement in any method.

e) Do not use break statements to exit loops.

f) Do not use global variables. If you are not sure if you are using them, ask.

g) Programs should be 100% your own work, as stated in the syllabus

Computer Science 282 Programming Assignment #1

Recall that a magic square is a 2-dimensional square array with n rows and n columns where each row, col, and diagonal add up to the same value. The value that every row, column, and diagonal adds up to is called the magic sum. For example, here is a magic square for the case n = 4 with a magic sum of 34:

6 10 7 11 3 8 9 14 12 1 16 5 13 15 2 4

If a size n magic square contains all of the number from 1 to n2 exactly once (as in the example above) we call this a standard magic square and it is not hard to show that the magic sum of a standard size n magic

square is n×(n2+1) 2

.

You are to write a program that will find standard magic squares in three different ways, by implementing the following 3 algorithms.

Purely random. Randomly put the numbers from 1 to n2 into an n × n array and then check to see if it is a magic square. Fill the array from top to bottom, left to right order. In other words, first fill the first row from left to right, then the second row, etc. Do this repeated until either a magic square is found or some limit for the number of tries is reached. The limit will be a parameter to your magic square method.

The hardest part of implementing this is finding an efficient way to it. For example, in the 4 × 4 case, how do we get the numbers from 1 to 16 randomly into the array? The way I did it was to create a 16 element array (in general you will create a n × n array) and put the numbers from 1 to 16 into that array. I then randomly found one of the 16 elements, put it into the magic square array, and switched that element to the end of the array so that I would never use it again. For the next step I randomly selected an element from the first 15 spots in the array, put that in the magic sum array, and then swapped it so that it is 1 from the end of the array.

Here’s how the example above got started. Let’s call my 16-element array num. It starts looking like this:

num: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

The algorithm found a random location in the 16-element array, in this case it’s location 5 with value 6, put the 6 in the first position of the magic square and then swapped that 6 with 16 at the end of the num array, giving us:

num: 1 2 3 4 5 16 7 8 9 10 11 12 13 14 15 6

Next the algorithm found a random location in the first 15 spots of num, in this case it was 10 which was then put into the magic square and moved to the right of num giving us:

num: 1 2 3 4 5 16 7 8 9 15 11 12 13 14 10 6

Continue this until the entire magic square array is filled.

If you have an alternative way for doing this bring it up in a Discussion. For finding random numbers you can either use Math.random or the Random class. Look these up in the

Java docs here and here. I think the Random class is easier to use but just be sure not to instantiate too many Random objects. You only need 1.

Last element of each row not random. This algorithm is the same as the purely random algorithm except when placing an element at the end of the row do not choose randomly but select the only element that works based on the magic sum. Looking at the 4 × 4 example above, the algorithm would have chosen 6, 10, and 7 randomly but now the only number that will work for the last spot is 11, so simply place that number in that spot in the array. The implementation of this is going to be similar to the purely random one, but you will need some addition code or methods to find the number for that last spot of each row. Don’t forget that it might not always be possible to find that last value. For example, suppose the first 3 random values put in the magic square array are 2, 3, and 5. Since the magic sum of a 4 × 4 array is 34 we would need the value 24, but the largest number available is 16.

You should notice that this algorithm finds solutions much faster than the purely random one. In fact, my purely random program only found solutions to n = 3 cases in a reasonable amount of time. n = 4 would frequently take more than 100,000,000 tries. But n = 4 works well with this algorithm, finding solutions quite quickly. The average number of tries necessary for this algorithm to find a magic square is just a little over 5,000,000.

Pair heuristic. This only works for cases where n is even and I will describe it for the n = 4 case. Recall that the magic sum for an n = 4 array is 34. Put elements randomly into the rows in pairs where each pair sums to 17, ½ the magic sum value. For example, here is a magic square found using that algorithm.

1 12 5 16 15 9 8 2 14 6 11 3 4 7 10 13

In this case the first random value found was 5. It was randomly placed in the first row. Notice this is different from how the other two algorithms work. 12 is the value that pairs with 5 to get to 17 so we place 12 randomly in one of the remaining open positions. The next random number found was 1 and it was placed randomly in one of the remaining positions and then its pair, 16, was placed in the only remaining spot in the first row.

This algorithm performs considerably better than the previous algorithm, requiring on average of only about 600,000 tries to find a solution.

I look forward to your thoughts about other general algorithms that will allow us to find magic squares for even larger n’s.

Below is an outline of the class and the methods that need to be implemented for that class. Do not make any changes to the classes, variables, names, etc. Just add code. Questions? Start or continue a Discussion.

This assignment is as much about following instructions as it is about programming. Be sure your methods do exactly what is expected of them and all rules mentioned below and in Canvas and class discussions are followed.

What follows are general rules that you must follow for this and, as applicable, all other programs you write in this class. Failure to follow these rules will cost you points.

1. I will eventually post a final test program. A sample test program is already posted to help get you started. Don’t wait for my final test program to appear to start debugging your program. You should begin testing with your own test programs. Also, the final test program I post may not be the same test program I run on your programs. You cannot assume your program is correct just because it works on the posted test program.

2. Submit your program through Canvas with the name prog1.java. Be sure that my main (test) program is in a different file from your class(es) and you should not submit my test program. Also, do not make your classes "public". If you deviate from any of these rules you will lose points because doing so makes it much more difficult for me to manage and test your programs.

3. The top of your prog1.java file (and all java code that you turn in to me in the future) should begin with comments that show: (i) Your name; (ii) Comp 282 and clear mention of what time your class meets; (iii) The assignment number; (iv) The date the assignment was handed in (which is not necessarily the same as the due date); (v) A brief description of what is contained in the file.

4. For all Java code you turn in: a) Choose clear and suggestive variable names. b) Be sure lines do not wrap to the first column of the next line or disappear off the end of the page. c) Use comments generously to describe how your methods work. Comments should appear

inside your methods, too – not just at the top. That said, don't overdo the comments. d) There should be no more than one return statement in any method. e) Do not use break statements to exit loops. f) Do not use global variables. If you are not sure if you are using them, ask. g) Programs should be 100% your own work, as stated in the syllabus.

import java.util.Random;

class MagicSquare {

private int size; private int[][] square;

// constructor — set the size and instantiate the array public MagicSquare(int size) {

}

// purely random — give up after "tries" tries public int purelyRandom(int tries) {

This is how I set up the main loop. I’m showing you as a hint. Yours can be different. But why mess with a good thing? 🙂

while (!found && tryCt < tries) {

}

This is how my method ends

if (found) return tryCt;

else return -1;

}

// force last number in each row public int endOfRow(int tries) {

while (!found && tryCt < tries) {

This is how I filled the magic square array. Many statements are missing, but this should give you some ideas. Notice the ok variable. If at any time a row cannot be finished there’s no point in continuing to later rows.

// fills rows one at a time for (row = 0; row < size && ok; row++) {

// put random values in all but the last spot for (col = 0; col < size – 1; col++) {

}

Following is the code to place the last element in a row. Again, you can change these lines if you like.

// call local method to find needed last element // num is the array described above. // “pick” points to that element in the num array pick = find(magicSum – rowsum, num, lastNum); if (pick == -1)

ok = false; else {

} } found = magic();

} if (found)

return tryCt; else

return -1; }

No hints for this one (yet), but it is hard. Concentrate on the first two algorithms and work on this as time allows. // put pairs of numbers in rows public int pairs(int tries) {

}

// determine if a magic square has been created, i.e., check all rows, columns, // and diagonals sum to the same value private boolean magic() {

}

// output the magic square (or whatever is in the array if it is not) public void out() {

int row, col; for (row = 0; row < size; row++) {

for (col = 0; col < size; col++) { System.out.print(String.format("%3d", square[row][col]));

} System.out.println();

} }

// change to false if this algorithm was not implemented public boolean endOfRowImplemented() {

return true; }

// change to false if this algorithm was not implemented public boolean putPairsinRowsImplemented() {

return true; }

// put your name here public static String myName() {

return "Alan Turing"; }

}

- Computer Science 282

,

public class test { public static void main(String[] args) { MagicSquare sq; int ct; sq = new MagicSquare(3); for (int i = 1; i <= 1; i++) { ct = sq.purelyRandom(10); System.out.print("Random " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 3, ct = 10 solution."); } else { System.out.println("Found n = 3, ct = 10 solution in " + ct + " tries."); sq.out(); } } System.out.println(); for (int i = 1; i <= 5; i++) { ct = sq.purelyRandom(1000000); System.out.print("Random " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 3, ct = 1,000,000 solution."); } else { System.out.println("Found n = 3, ct = 1,000,000 solution in " + ct + " tries."); sq.out(); } } System.out.println(); sq = new MagicSquare(4); for (int i = 1; i <= 1; i++) { ct = sq.purelyRandom(10); System.out.print("Random " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10 solution."); } else { System.out.println("Found n = 4, ct = 10 solution in " + ct + " tries."); sq.out(); } } System.out.println(); for (int i = 1; i <= 1; i++) { ct = sq.purelyRandom(10000000); System.out.print("Random " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10,000,000 solution."); } else { System.out.println("Found n = 4, ct = 1,000,000 solution in " + ct + " tries."); sq.out(); } } System.out.println(); if (sq.endOfRowImplemented()) { sq = new MagicSquare(3); for (int i = 1; i <= 1; i++) { ct = sq.endOfRow(10); System.out.print("End of row " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 3, ct = 10 solution."); } else { System.out.println("Found n = 3, ct = 10 solution in " + ct + " tries."); sq.out(); } } System.out.println(); for (int i = 1; i <= 5; i++) { ct = sq.endOfRow(10000); System.out.print("End of row " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 3, ct = 10,000 solution."); } else { System.out.println("Found n = 3, ct = 10,000 solution in " + ct + " tries."); sq.out(); } } System.out.println(); sq = new MagicSquare(4); for (int i = 1; i <= 1; i++) { ct = sq.endOfRow(10); System.out.print("End of row " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10 solution."); } else { System.out.println("Found n = 4, ct = 10 solution in " + ct + " tries."); sq.out(); } } System.out.println(); for (int i = 1; i <= 5; i++) { ct = sq.endOfRow(10000000); System.out.print("End of row " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10,000,000 solution."); } else { System.out.println("Found n = 4, ct = 10,000,000 solution in " + ct + " tries."); sq.out(); } } System.out.println(); } else System.out.println("End of row trick not implemented.n"); if (sq.putPairsinRowsImplemented()) { sq = new MagicSquare(4); for (int i = 1; i <= 1; i++) { ct = sq.pairs(10); System.out.print("Pairs " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10 solution."); } else { System.out.println("Found n = 4, ct = 10 solution in " + ct + " tries."); sq.out(); } } System.out.println(); for (int i = 1; i <= 5; i++) { ct = sq.pairs(10000000); System.out.print("Pairs " + i + ": "); if (ct == -1) { System.out.println("Failed to find an n = 4, ct = 10,000,000 solution."); } else { System.out.println("Found n = 4, ct = 10,000,000 solution in " + ct + " tries."); sq.out(); } } } else System.out.println("Pairs trick not implemented."); System.out.println("n" + MagicSquare.myName() + " program has completed."); } }

Our website has a team of professional writers who can help you write any of your homework. They will write your papers from scratch. We also have a team of editors just to make sure all papers are of HIGH QUALITY & PLAGIARISM FREE. To make an Order you only need to click Ask A Question and we will direct you to our Order Page at WriteDemy. Then fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline.

Fill in all the assignment paper details that are required in the order form with the standard information being the page count, deadline, academic level and type of paper. It is advisable to have this information at hand so that you can quickly fill in the necessary information needed in the form for the essay writer to be immediately assigned to your writing project. Make payment for the custom essay order to enable us to assign a suitable writer to your order. Payments are made through Paypal on a secured billing page. Finally, sit back and relax.

**About Wridemy**

We are a professional paper writing website. If you have searched a question and bumped into our website just know you are in the right place to get help in your coursework. We offer **HIGH QUALITY & PLAGIARISM FREE** Papers.

**How It Works**

To make an Order you only need to click on **“Order Now”** and we will
direct you to our Order Page. Fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline.

**Are there Discounts?**

All new clients are eligible for 20% off in their first Order. Our payment method is safe and secure.

__Hire a tutor today __**CLICK HERE** to make your first order

**CLICK HERE**to make your first order