Extra: Magic Squares

posted by: Ms. Martin 9 February 2010 No Comment

An nxn matrix that is filled with the numbers 1, 2, 3 … n² is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value.

Square

Write a class Square with a constructor that takes in an integer matrix.  You will write the following instance methods:

  • boolean method to check whether each number 1 – n² occurs exactly once
  • int method that computes the row sum
  • int method that computes the column sum
  • int method that computes the diagonal sum
  • isMagic method that returns whether or not the square is magic

MagicSquare

Write a class MagicSquare with a constructor that constructs a magic square based on this algorithm.  You may want to pick a random initial value to make things interesting.  Your class should also have a toString method that returns a representation of the square.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>