Monday, September 21, 2009

The Magic in the Square

for an odd-n magic square, use de la loubere's algorithm which can be expressed as :
(1)begin by placing a 1 in the middle location of the top row:
(2)now put successive integers in an upward-right diagonal path
**(3)if the upward-right movement results in a location outside the boundaries of the square, place the new number at the opposite end of the row or column that would contain the new number, if the rows and columns were not bounded
**(4)if the upward-right square is already occupied, place the new number directly below the current one




convert that to pseudo code first then translate it into any desired programming language.

the following is created using c#.

//form level declaration
    int[,] magicSquare = new int[15, 15];
---------------------------------------------
private void btnGenerate_Click(object sender, EventArgs e)
{
   int dimension = Convert.ToInt32(this.cboSize.Text);
   this.populateMagicSquare(dimension);
   this.generateMagicSquare(dimension);
   this.setDataGrid(dimension);
}
---------------------------------------------
private void populateMagicSquare(int size)
{// populate magicSquare array with zeroes
   for (int row= 0; row < size; row++)
       for (int col = 0; col < size; col++)
         magicSquare[row, col] = 0;
}
---------------------------------------------
private void generateMagicSquare(int size)
{
   int curr_row = 0;
   int curr_col = size / 2;
   int temp_row = curr_row;
   int temp_col = curr_col;

   magicSquare[curr_row, curr_col] = 1; // (1)

   for (int ctr = 2; ctr <= size * size; ctr++)
{
      if (curr_row - 1 >= 0)
          temp_row = curr_row - 1; // (2)
      else
          temp_row = size - 1; // (3)

       if (curr_col + 1 < size)
          temp_col = curr_col + 1;
       else
          temp_col = 0;

       if (magicSquare[temp_row, temp_col] != 0)
          curr_row++; // (4)
       else
       {
          curr_row = temp_row;
          curr_col = temp_col;
       }
       magicSquare[curr_row, curr_col] = ctr;
   }
}
---------------------------------------------
private void setDataGrid(int size)
{
   this.dgvMagicSquare.Rows.Clear();
   this.dgvMagicSquare.ColumnCount = size;
   this.dgvMagicSquare.Rows.Add(size-1);

   for( int row=0; row < size; row++)
       for (int col=0; col < size; col++)
          this.dgvMagicSquare[col, row].Value = magicSquare[row,col].ToString();
}
---------------------------------------------
***end of program***

1 comment:

  1. interesting title! you lured me not to the world of "magic" but to something else i've cursed a long time ago hehehe! :-)

    ReplyDelete