c++ - 完成幻方发生器

标签 c++ algorithm generator

此代码仅对奇数 N 运行。问题是没有想法如何添加对偶数 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;
}

如果能提供有关故障排除的提示,我将不胜感激。

如果我没记错的话,问题出在这一行:

int i = 0, j = n / 2;

但我不知道如何更改代码以支持偶数

最佳答案

我假设您指的是普通幻方(其中数字限制为 1,2..n^2)

首先,对于n=2,构造这样的幻方是不可能的。

第二,你需要一个全新的算法,这要复杂得多。问题(为任何偶数构造幻方)已解决in this paper虽然那里没有任何伪代码,但解释的实现非常简单(虽然很长)。

关于c++ - 完成幻方发生器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336150/

相关文章:

python - 如何用递归生成器遍历二叉树?

c++ - 运行时错误 : reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (STL_vector. h)

c# - 是否有任何算法可以在给定定义形状的坐标的情况下计算形状的面积?

java - 给定 inDigits 的基础否定

algorithm - 如何用MapReduce/Hadoop实现特征值计算?

python - 是来自 python 的 for/while 循环是一个生成器

Python 生成器的 'yield' 在单独的函数中

c++ - 将空 vector 传递给对象的 "correct"方法是什么?

c++ - 为什么 C++ 代码必须包含在函数中?

c++ - Fork() 在 switch-case 中打印多个 case