幾天前我發佈了一個關於爲這個數獨謎題生成隨機框的問題。現在我很難爲它生成邊界線。它應該是這樣的: 爲數獨謎題創建邊框線
但我不能拿出代碼來做到這一點。問題在於第0到第8行被數獨數字佔據,我不知道如何將這些'|'和這些數字之間的' - '字符,以及我猜想的邊界。
這是我到目前爲止已經試過:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int column_random [81], row_random [81], n = 3, k, j, input, number;
char check = '0';
printf("Enter percentage of empty squares: ");
scanf("%d", &input);
srand (time (NULL));
number = (input * 81)/100 ;
for (k = 0; k < number; k++)
{
row_random [k] = rand() % 9 ;
column_random [k] = rand() % 9 ;
for (j = 0; j < k; j++)
{
if (row_random [j] == row_random [k] && column_random [j] == column_random [k])
{
row_random [k] = rand() % 9 ;
column_random [k] = rand() % 9 ;
j = -1;
}
}
}
for (int i = 0; i <= 9; i++)
{
if (i == 0)
{
for (i = 1; i <= 27; i++)
{
printf("-");
}
printf("\n");
}
}
for (int j = 0; j <= 9; j++)
{
if (j == 0)
{
for (int i = 1; i <= 9; i++)
{
printf("|");
printf("\n");
}
}
}
for (int i = 0; i < n*n; i++)
{
for (int j = 0; j < n*n; j++)
{
for (k = 0; k < number; k++)
{
check = '0';
if (j == column_random [k] && i == row_random [k])
{
check = '1';
break;
}
else
{
check = '0';
}
}
if (check == '1')
{
printf(" ");
}
else
{
printf(" %d ",(i*n + i/n + j) % (n*n) + 1);
}
}
printf("\n");
}
return 0;
}
這裏是我的執行跟蹤:
Enter percentage of empty squares: 50
---------------------------
|
|
|
|
|
|
|
|
|
1 3 4 5 7 8 9
4 5 8 9 2
8 3 4 5
2 3 6 7 1
8 2 4
2 4 5 7
3 5 6 2
8 9 2 4 5
9 1 2 3
------------------
(program exited with code: 0)
我真的不知道該如何解決這個問題。我認爲在打印數字時增加空格應該爲打印邊緣提供足夠的空間,但似乎並不如此。誰能幫我?謝謝!
編輯:感謝大家的所有幫助!雖然不是完全一樣的畫面,我已經與一些接近來它,下面是我的提高代碼:
for (int i = 0; i <= n*n; i++)
{
if (i == 9)
{
for (int x =0; x <= 30; x++)
{
printf("-");
}
printf("\n");
break;
}
if (i == 0 || i == 3 || i == 6)
{
for (int x =0; x <= 30; x++)
{
printf("-");
}
printf("\n");
}
for (int j = 0; j < n*n; j++)
{
for (k = 0; k < number; k++)
{
check = '0';
if (j == column_random [k] && i == row_random [k])
{
check = '1';
break;
}
else
{
check = '0';
}
}
if (check == '1')
{
if (check == '1' && (j == 0 || j == 3 || j == 6))
{
printf("| ");
}
else if (check == '1' && j == 8)
{
printf(" |");
}
else
{
printf(" ");
}
}
else
{
if (j == 0 || j == 3 || j == 6)
{
printf("|%2d ",(i*n + i/n + j) % (n*n) + 1);
}
else if (check == '0' && j == 8)
{
printf("%2d |",(i*n + i/n + j) % (n*n) + 1);
}
else
{
printf("%2d ",(i*n + i/n + j) % (n*n) + 1);
}
}
}
printf("\n");
}
只是一個更新,我會通過所有改進建議,以及!
你的程序將你告訴它打印打印一切**在爲了告訴它**。所以如果你有一個在**之前打印'| \ n' **的循環,你甚至可以打印你的棋盤,當然這是你會得到的輸出。 – StoryTeller
這裏的訣竅是認識到你必須一次打印整行。你不能打印所有的左邊,然後是所有的數字,然後右邊的條。相反,打印頂部(它永遠不會改變),然後使用'printf'語句打印帶有數字的行。它應該是''%c%c%c |%c%c%c |%c%c%c |',然後以數字形式提供數字作爲字符,如果您知道的話,或者如果您不知道,則使用空間數據庫 –
原來如此。所以我不能單獨打印邊框線,對吧? –