我想用c ++初始化一个数独板(9 * 9)。得到一个空白的屏幕,闪烁的光标作为输出。 [英] i'm tring to initialise a sudoku board (9*9) using c++.getting a blank screen with blinking cursor as output.
本文介绍了我想用c ++初始化一个数独板(9 * 9)。得到一个空白的屏幕,闪烁的光标作为输出。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
// here array board[][] is declared to be a global variable
int board[9][9];
/* this function returns a random number in the specified range(excluding the upper limit)
in this program,returns random number between 0 and 8 */
int randrange(int low,int high)
{
return rand()%(high-low)+low;
}
bool check(int num,int row,int col)
{
int i;
// checks if number is repeated in that row or not
for(i=0;i<9;i++)
{
if(board[row][i]==num)
{
return false;
}
}
// checks if number is repeated in that column or not
for(i=0;i<9;i++)
{
if(board[i][col]==num)
{
return false;
}
}
return true;
}
/* this function checks if that particular element in the array 'board' is already assigned
a value or not */
bool non_empty(int row,int col)
{
//0 is default value
if(board[row][col]==0)
return true;
// true indicates unassigned element
else return false;
// false indicates an element which is already assigned a value
}
// a class handiling all the inintialisation part of the board
class initialisation
{
private:
int num,i,j,row,col;
bool flag=true;
public:
void _initialisation();
void display();
};
void initialisation::_initialisation()
{
// in the for loop below ,numbers from 1 to 9 are assigned to the array board[][]
//the row and column index are chosen at random
for(num=1;num<=9;num++)
{
flag=true;
for(i=0;i<9;i++)
{
do
{
row=randrange(0,9);
col=randrange(0,9);
/* in this if statement we perform calls to two functions
non_empty(row,col) returns true only if that element in the
array board is not assigned a value earlier,if not returns false.
check(num,row,col) returns true only if that particular number 'num' is not
repeated in that row and column */
if(non_empty(row,col)&&(check(num,row,col)==true))
{
flag=true;
board[row][col]=num;
}
else
flag=false;
} while(flag==false);
}
}
}
//this method displays the elements in array board[][]
void initialisation::display()
{
for(i=0;i<9;i++)
{
for(j=0;j<9;j++)
cout<<board[i][j]<<" ";
cout<<endl;
}
}
//main function starts here
int main()
{
srand(time(NULL));
// we create an object of the class initialisation
initialisation a;
// we call two methods of the class initialisation below
a._initialisation();
a.display();
return 0;
}
推荐答案
你没有问过一个问题,所以我只能帮助解决一个但很重要的问题。关于你的主要问题是硬编码立即常量 9.将它声明为显式常量,否则你的代码将无法支持。
-SA
You did not ask a single question, so I can only help with one but important fix. On of your major problems is hard-coding the immediate constant 9. Declare it as an explicit constant, otherwise your code would be unsupportable.
—SA
这篇关于我想用c ++初始化一个数独板(9 * 9)。得到一个空白的屏幕,闪烁的光标作为输出。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文