我必須在 C 中創建具有以下模式的數獨網格:
1 2 3 4
3 4 1 2
2 3 4 1
4 1 2 3
左上角的第一個數字(此處為 1)必須是可編輯變數的起始值。還有另一個變數可以用正方形大小創建網格,在這個例子中,正方形大小是 2 并且 1 2 3 4 在一個正方形中。3 4 1 2 在另一個方格中,依此類推...
如果起始值為例如 3,則網格如下所示:
3 4 1 2
1 2 3 4
4 1 2 3
2 3 4 1
我注意到有一個模式:如果行號是奇數,則下一行的新起始值是倒數第二個。如果行號為偶數,則下一行的新起始值為最后一行。我試圖在 C 中做到這一點,但偶數行正在克隆自己。請注意,此處不允許使用陣列和指標,只能使用回圈和其他控制結構。
我嘗試了以下方法,但偶數行正在克隆自己:
#include <stdio.h>
const int intSquareSize = 2;
const int intFieldLength = intSquareSize * intSquareSize;
int intStartValue = 3;
int main() {
int a = 0;
int b = 0;
int m = 0;
for (int intRowCounter = 1; intRowCounter <= intFieldLength; intRowCounter ) {
m = intFieldLength - 1;
for (int intColumnCounter = 1; intColumnCounter <= intFieldLength; intColumnCounter ) {
a = intStartValue (intColumnCounter - 1);
b = a;
if (a > intFieldLength) {
a = intFieldLength - m;
m--;
}
if (intRowCounter % 2 == 0 && intColumnCounter == intFieldLength) {
intStartValue = a;
} else if (intRowCounter % 2 == 1 && intColumnCounter == (intFieldLength - 1)) {
intStartValue = b;
}
printf("%d\t", a);
}
printf("\n");
}
return 0;
}
我做錯了什么,我該如何解決?
uj5u.com熱心網友回復:
如果行號為奇數,則下一行的新起始值為倒數第二個。如果行號為偶數,則下一行的新起始值為最后一行。
我認為用奇數和偶數來思考是沒有幫助的。所涉及的數字只是符號,甚至可以用不同的顏色替換它們(例如)。奇數/偶數在這里并不是什么重要的事情,而且它肯定不會在其他電路板尺寸中發揮同樣的作用。
我看到的模式是這樣的:
在第一intSquareSize行中,值水平移動(與前一行相比)intSquareSize。例如,intSquareSize=3前三行可能是:
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8
注意下一行向左移動 3 個位置。
那么接下來的intSquareSize行塊的模式將是相同的,但有一個班次。所以完整的 9x9 數獨應該是這樣的:
3 4 5 6 7 8 9 1 2
6 7 8 9 1 2 3 4 5
9 1 2 3 4 5 6 7 8
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
1 2 3 4 5 6 7 8 9
5 6 7 8 9 1 2 3 4
8 9 1 2 3 4 5 6 7
2 3 4 5 6 7 8 9 1
這只是您可以遵循的一種可能模式。可能還有其他人。但是下面的代碼將應用上述邏輯。注意我使用了你的變數,但我更喜歡使用從 0 開始的邏輯,所以回圈變數從 0 開始,并且 的值a也是從 0 開始的。只有在列印時 1 才被加到那個值上,所以它變成基于 1 的:
int a = intStartValue - 1; // Move from 1-based to 0-based
for (int intBlockCounter = 0; intBlockCounter < intSquareSize; intBlockCounter ) {
for (int intRowCounter = 0; intRowCounter < intSquareSize; intRowCounter ) {
for (int intColumnCounter = 0; intColumnCounter < intFieldLength; intColumnCounter ) {
printf("%d\t", (a 1)); // back to 1-based
a = (a 1) % intFieldLength;
}
printf("\n");
a = (a intSquareSize) % intFieldLength; // Shift within a block
}
a = (a 1) % intFieldLength; // Shift between blocks
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523804.html
標籤:Cfor循环数独控制结构
