C++ Programming Exercise: Implement a function bool** aListToMatrix(vector<int>
ID: 661376 • Letter: C
Question
C++ Programming Exercise:
Implement a function
bool** aListToMatrix(vector<int> aLists[], int size);
that returns on adj. matrix equivalent to aLists(adj lists)
Here is my solution:
bool **aListToMatrix(vector<int> aList[], int size){
bool** arr = new bool*[size];
for(int i = 0; i < size; ++i)
arr[i] = new bool[size];
for(int j=0; j<size;j++){
for(int k=0; k<(aList+j)->size(); k++){
for(int t=0; t<size; t++){
if((aList+j)->at(k)==t)
*(*(arr+t)+j) = true;
else
*(*(arr+t)+j) = false;
}
}
}
return arr;
}
Can someone give me the code for the main() function to test the other function?
Explanation / Answer
//Program for adjacency matrix using vector
#include <iostream>
#include <vector>
using namespace std;
//Your implemented function
bool **aListToMatrix(vector<int> aList[], int size){
bool** arr = new bool*[size];
for(int i = 0; i < size; ++i)
arr[i] = new bool[size];
for(int j=0; j<size;j++){
for(int k=0; k<(signed)(aList+j)->size(); k++){ //Getting warning! so that unsinged to signed casting is done
for(int t=0; t<size; t++){
if((aList+j)->at(k)==t)
*(*(arr+t)+j) = true;
else
*(*(arr+t)+j) = false;
}
}
}
return arr;
}
//My code of main
int main()
{
int i,j;//for index positions
bool **arr=NULL; //initially null
vector<int> aList(5); //05 nodes are taken
for(i=1;i<=5;i++)
{
aList.push_back(i); //Adding elements to vector
}
arr=aListToMatrix(&aList,5); //Calling adjacency matrix array function
for(i=0;i<5;i++) //outer loop for rows
for(j=0;j<5;j++) //Inner loop for columns
cout<<" "<<arr[i][j]; //Printing of adjacency matrix
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.