the goal of this code is to create a matrix of userNum x userNum size of distict
ID: 3791502 • Letter: T
Question
the goal of this code is to create a matrix of userNum x userNum size of distict random integers.
How can the printing for loop and vector creating for loop be rewritten into separate functions?
do
{
do
{
cout << " Enter the size of the matrix: ";
cin >> userNum;
if (userNum < 2 && !isdigit(userNum))
cout << " Error *** Must be an integer greater than 2" << endl;
} while(userNum < 2);
vector<vector<int> > randMatrix;
cout << " The perfect matrix that is created for size " << userNum << ":" << $
srand(time(NULL));
for (int i = 0; i < userNum; i++){
vector<int> row;
for(int j = 0; j < userNum; j++){
while ((rand() % 10) != row[i]){
row.push_back(rand() % 10);
}
}
randMatrix.push_back(row);
}
for(int i = 0; i < randMatrix.size(); i++){
for(int j = 0; j < randMatrix[i].size(); j++){
cout << randMatrix[i][j] << " ";
}
cout << endl;
}
Explanation / Answer
Below code is modified according to the seperate functions for creating and printing the matrix :
do
{
do
{
cout << " Enter the size of the matrix: ";
cin >> userNum;
if (userNum < 2 && !isdigit(userNum))
cout << " Error *** Must be an integer greater than 2" << endl;
} while(userNum < 2);
vector<vector<int> > randMatrix;
cout << " The perfect matrix that is created for size " << userNum << ":" << $
createVector(&randMatrix,userNum);
printMatrix(&randMatrix);
}
// Seperate methods for creating and printing matrix
int createVector(vector<vector<int> > *randMatrix, int userNum){
srand(time(NULL));
for (int i = 0; i < userNum; i++){
vector<int> row;
for(int j = 0; j < userNum; j++){
while ((rand() % 10) != row[i]){
row.push_back(rand() % 10);
}
}
randMatrix.push_back(row);
}
}
int printMatrix(vector<vector<int> > *randMatrix){
for(int i = 0; i < randMatrix.size(); i++){
for(int j = 0; j < randMatrix[i].size(); j++){
cout << randMatrix[i][j] << " ";
}
cout << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.