Warmachine28

sparseMultiplication

Jan 9th, 2022 (edited)
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. void sparseMultiplication(vector<vector<int>> firstMatrix, vector<vector<int>> secondMatrix);
  8.  
  9. void sparseMultiplication(vector<vector<int>> firstMatrix, vector<vector<int>> secondMatrix)
  10. {
  11.     if(firstMatrix[0].size() != secondMatrix.size())
  12.     {
  13.         cout<<"Multiplication is not possible"<<endl;
  14.         return;
  15.     }
  16.    
  17.     vector<vector<int>> resultMatrix(firstMatrix.size(),vector<int>(secondMatrix[0].size()));
  18.  
  19.     for(int i = 0; i < firstMatrix.size();i++)
  20.     {
  21.         for(int j = 0; j < firstMatrix[0].size(); j++)
  22.         {
  23.             if(firstMatrix[i][j] != 0)
  24.             {
  25.                 for(int k = 0; k < secondMatrix[0].size(); k++)
  26.                 {
  27.                     if(secondMatrix[j][k] != 0 )
  28.                     {
  29.                         resultMatrix[i][j] += firstMatrix[i][j] * secondMatrix[j][k];
  30.                     }
  31.                    
  32.                    
  33.                 }
  34.             }
  35.                
  36.            
  37.         }
  38.     }
  39.  
  40.     for(int i=0;i<resultMatrix.size();i++)
  41.     {
  42.         cout<<"{ ";
  43.         for(int j=0;j<resultMatrix[0].size();j++)
  44.         {
  45.             cout<<resultMatrix[i][j];
  46.         }
  47.         cout<<" }"<<endl;
  48.     }
  49.  
  50. }
  51. int main()
  52. {
  53.     vector<vector<int>> firstMatrix =
  54.     {
  55.         {1, 0, 0},
  56.         {-1, 0, 3}
  57.     };
  58.    
  59.     vector<vector<int>> secondMatrix =
  60.     {
  61.         {7, 0, 0},
  62.         {0, 0, 0},
  63.         {0, 0, 1}
  64.     };
  65.     sparseMultiplication(firstMatrix,secondMatrix);
  66.  
  67.     return 0;
  68. }
Add Comment
Please, Sign In to add comment