In: Computer Science
Write a function that will accept one integer matrix E and one column vector F by reference parameters, and one integer I as a value parameter. The function will return an integer v, which is the i-th coefficient of row vector denoted by E*F (multiplication of E and F). For example, if V = E*F, the function will return v, which is equal to V[i].
Explain the time complexity of this function inside of the function code as a comment.
in c++ program
Program :
//here this program is not with dynamically allocated memory because we can not pass by reference an array with unknown bound so we need to pass the size also
//we can make this dynamic by use of pointers
//time complexity of the function will be O(n) where n is no of cols in matrix E or no of rows in col vector F
as we just need to return the coefficient i of V where V = E*F
so don't need to find all the coefficients just need find the coefficient for ith row of E
1 2 3 1 14 = (1*1 + 2*2 + 3*3)
4 5 6 X 2 = 32 = (4*1+ 5*2+6*3)
7 8 9 3 50 = (7*1+8*2+9*3)
main.cpp
#include <iostream>
#include <vector>
using namespace std;
//Required function
//we can not pass reference array of unkown bound
int findCoefficient(int (&E)[3][3],vector<int> &F,int i)
{
int row1 = sizeof(E)/sizeof(E[0]); //no of rows in matrix E
int col1 = sizeof(E[0])/sizeof(int); // no of cols in matrix E
int row2 = F.size(); // no of rows in F
if(i < 0 || i>= row1)
{
cout<<"\nCoefficient index is out of range!";
return -1;
}
if(col1 != row2)
{
cout<<"\nMultipliction is not possible!";
return -1;
}
int v=0; // to store value of V[i] where V = E*F index i = 0 to row1-1
/***
* here loop is going from 1 to (no of cols in E or no of rows in F)
*therefore the time complexity = O(n) where n is no of cols in matrix E or no of rows in vector F
*here we don't need to find all multiplications we just need to find the multiplication for the
ith Coefficient of E*F so we will consider all cols of ith row in matrix E and all rows of vector F
***/
for(int j=0; j<col1; j++)
{
v = v + E[i][j]*F[j];
}
return v;
}
//main program for testing the function
int main()
{
int E[][3]= {{1,2,3},{4,5,6},{7,8,9}};
vector<int> F;
F.push_back(1);
F.push_back(2);
F.push_back(3);
//entring the index to find v[i]
int index;
cout<<"\nEnter the Coefficient index i = (0 to row-1) to find V[i] where V = E*F : ";
cin>>index;
//calling the function
int v = findCoefficient(E,F,index);
cout<<"\nValue of V["<<index<<"]= "<<v;
return 0;
}
Output :
Program screenshot :