kiriart
kiriart

Reputation: 27

Finalize the magic square generator

This code that runs only for odd N. The problem is that there are no ideas how to add support for even values N

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    setlocale(0, "");
    int n;
    cout << "Enter the size of the magic square - ";
    cin >> n;

    int **matrix = new int *[n];
    for (int i = 0; i < n; ++i)
    {
        matrix[i] = new int[n];
    }

    int nsqr = n * n;
    int i = 0, j = n / 2;

    for (int k = 1; k <= nsqr; ++k)
    {
        matrix[i][j] = k;
        i--;
        j++;
        if (k % n == 0)
        {
            i += 2;
            --j;
        }
        else
        {
            if (j == n)
            {
                j -= n;
            }
            else if (i < 0)
            {
                i += n;
            }
        }
    }

    cout << "\n\nMagic square size - " << n << "\n\n";
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }

    for (i = 0; i < n; i++)
        delete[] matrix[i];
    delete[] matrix;

    system("pause >> null");
    return 0;
}

I would be grateful for tips on troubleshooting.

If i'm not mistaken, the problem is in this line:

int i = 0, j = n / 2;

But i don't know how to change the code to support even values

Upvotes: 1

Views: 219

Answers (3)

kiriart
kiriart

Reputation: 27

I found answer on my question in this artcile I made full revision my algorithm based on this article. Later posted listing the resulting program

Upvotes: 0

Raindrop7
Raindrop7

Reputation: 3911

the problem is here:

i = 0;
int j = n / 2;

for (int k = 1; k <= nsqr; ++k)
{
    matrix[i][j] = k;
    i--;
}

look how you decrement i inside the loop and making it as an index of the array so:

 matrix[-3][j] = k; // will be in your code

you are messing deliberately with the indexes of the array

Upvotes: 0

pio
pio

Reputation: 540

I would assume that you meant normal magic square (where the number are restricted to 1,2..n^2)

First of all, it's impposible to construct such magic square for n=2.

2nd, you would need an whole new algorithm for it, which is much more complicated. The problem (constructing magic square for any even number) is solved in this paper and while there isn't any psaudo code there, the implementation from the explenation is quite straightforward (long one though).

Upvotes: 1

Related Questions