In: Computer Science
Write a C++ program that :
1. Allow the user to enter the size of the matrix such as N. N must be an integer that is >= 2 and < 11.
2. Create an vector of size N x N.
3. Call a function to do the following : Populate the vector with N2 distinct random numbers. Display the created array.
4. Call a function to determines whether the numbers in n x n vector satisfy the perfect matrix property. Look at the sample run for the exact output
5. Repeat steps 1 - 4 until the user terminates the program.
The program needs a main and 2 functions
If you have any doubts, please give me comment...
#include <iostream>
#include <vector>
using namespace std;
bool isExisted(vector<vector<int>> matrix, int value);
void generateMatrix(vector<vector<int>> &matrix);
void printMatrix(vector<vector<int>> matrix);
bool isPerfectMatrix(vector<vector<int>> matrix);
int main()
{
int N;
string choice;
do{
cout<<"Enter the size of the matrix: ";
cin>>N;
while(N<2 || N>11){
cout<<"Size must be >= 2 and < 11. Re-enter: ";
cin>>N;
}
vector<vector<int>> matrix(N);
for(int i=0; i<N; i++)
matrix[i] = vector<int>(N);
generateMatrix(matrix);
cout<<"Generated Matrix is: "<<endl;
printMatrix(matrix);
if(isPerfectMatrix(matrix))
cout<<"Perfect Matrix"<<endl;
else
cout<<"NOT a Perfect Matrix"<<endl;
cout<<"\nDo you want to continue? ";
cin>>choice;
}while(choice=="Y" || choice=="y");
}
bool isExisted(vector<vector<int>> matrix, int value){
for(int i=0; i<matrix.size(); i++){
for(int j=0; j<matrix.size(); j++){
if(matrix[i][j]==value)
return true;
}
}
}
void generateMatrix(vector<vector<int>> &matrix){
int size = matrix.size();
for(int i=0; i<size; i++){
for(int j=0; j<size; j++){
int num = (rand()%1000)+1;
if(!isExisted(matrix, num))
matrix[i][j] = num;
}
}
}
void printMatrix(vector<vector<int>> matrix){
for(int i=0; i<matrix.size(); i++){
for(int j=0; j<matrix.size(); j++){
cout<<matrix[i][j]<<"\t";
}
cout<<endl;
}
}
bool isPerfectMatrix(vector<vector<int>> matrix)
{
int sum = 0;
int size = matrix.size();
for (int i = 0; i < size; i++)
sum = sum + matrix[i][i];
for (int i = 0; i < size; i++)
{
int rowSum = 0;
for (int j = 0; j < size; j++)
rowSum += matrix[i][j];
if (rowSum != sum)
return false;
}
for (int i = 0; i < size; i++)
{
int colSum = 0;
for (int j = 0; j < size; j++)
colSum += matrix[j][i];
if (sum != colSum)
return false;
}
return true;
}