Hello. I have made a square matrix of order nxn with random values in it. The entries are 1 to n appearing randomly as desired. Now i would like to limit all entries to appear strictly n times. for e.g. in the code below the output is a 9x9 matrix with entries 1 to 9. I want every number to appear only 9 times in the matrix to make it look like a sudoku. So how to do that?
Code:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int ROWS = 9; const int COLS = 9; //no more magic numbers. Named type now typedef int Matrix[ROWS][COLS]; int getrandomval(); void fillrandom(Matrix mat) { for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { mat[row][col] = getrandomval(); } } } int getrandomval() { int x = 0; x = rand() % 9 + 1; return x; } void show(Matrix m) { for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLS; col++) { cout << " " << m[row][col] << " "; } cout << endl; } cout << endl; } int main() { srand(time(0)); //using our constant cout << "\nGenerating the random number matrix of order" << ROWS << " x " << COLS << "...\n\n\n"; Matrix mat; //declaring the variable getrandomval(); fillrandom(mat); //filling our variable show(mat); //showing whats in the matrix return 0; }
Comment