簡體   English   中英

幻方算法問題

[英]Magic Square Algorithm Issue

我正在遵循de la Loubere的算法,並嘗試將其編碼為適用於我的Magic Square程序的成功算法。 我正在按照以下步驟操作:

1)數字“ 1”位於第一行的中間。

2)然后,所有數字都放在前一個數字的右一列和上一行。

3)每當下一個號碼放置在最上面一行的上方時,請留在該列中並將該號碼放置在最下面一行。

4)每當下一個號碼放置在最右邊的列之外時,請留在該行並將號碼放置在最左邊的列中。

5)遇到實心正方形時,將下一個數字直接放在前一個數字的下方。

6)當下一個數字位置在行和列之外時,將數字直接放在前一個數字的下方。

但是,我沒有得到期望的數字輸出。 (也就是說,數字不在正確的位置或正在注冊為零。)

我們將不勝感激。(由於上述代碼中的某些原因,最后一個尖括號在代碼塊之外。但這不是問題。)

編輯:我已經根據建議編輯了代碼,但是我仍然發現相同的錯誤:

void magic(unsigned int n){//Takes in size of square (User input)
unsigned int magicSq[15][15];
unsigned int sizeSquared = n * n; 
int i = 0, j = n/2; //the initial position according to de la Loubere's algorithm
unsigned int indexer; //What we are going to use to iterate through

//Using de la Loubere's algorithm for odd # magic squares
for (indexer = 1; indexer <= sizeSquared; indexer++){
    magicSq[i][j] = indexer;
    i--; //Decrement the row (one row up)
    j++; //Increment the column (One column to the right)

    //First ensure with if and else if that i and j are in bounds.
    if (i < 0){//If row goes higher than top row
        i += n; //i is set to bottom row
    }

    else if(j == n){//If number placement is outside of rightmost column
        j -= n; //Maintain row and place # in leftmost column.
    }

    else{
        if (magicSq[i][j] != 0 || (i < 0 && j ==n )){//If the magic square has a number in it
                                            //Or is outside both row and column
            i++; //Place the number one below the previous number 
        }
    }

}

}

if (magicSq != 0 || (i < 0 && j ==n )){//If the magic square has a number in it

您的代碼與此處的注釋不符。 magicSq始終將為非零。 您想要magicSq[i][j]!=0

但是在您可以執行該測試或任何測試之前,請先檢查ij是否在范圍內,然后根據需要進行調整。

問題似乎在於,您先向右移動1步,然后再向右移動1步,如果您碰到另一個數字,則向下移動1步。 使用這種方法,您實際上應該向下移動2步,然后向左移動1步,以最終比原始位置低1步。 我對邏輯進行了一些修改,這似乎可以正常工作:

for (indexer = 1; indexer <= sizeSquared; indexer++){
    //If the magic square has a number in it, redo move and go one down
    if (magicSq[i][j] != 0){            
        i += 2;
        j -= 1;
    }
    magicSq[i][j] = indexer;
    if (i == 0 && j == n - 1) //if in top right corner, move down
        i++;
    else{
        i--; //Decrement the row (one row up)
        j++; //Increment the column (One column to the right)
    }
    if (i < 0){//If row goes higher than top row
        i += n; //i is set to bottom row
    }
    else if (j == n){//If number placement is outside of rightmost column
        j -= n; //Maintain row and place # in leftmost column.
    }
}

在3x3的正方形上,我得到的結果是:

8 1 6
3 5 7
4 9 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM