Skip to content

Instantly share code, notes, and snippets.

@fa7ad
Last active November 8, 2018 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fa7ad/d109e9130b05f32050707ce80be9acf8 to your computer and use it in GitHub Desktop.
Save fa7ad/d109e9130b05f32050707ce80be9acf8 to your computer and use it in GitHub Desktop.
MatrixChainMult.cpp
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
template <int T>
void multMatrix(array<array<int, T>, T> a, array<array<int, T>, T> b,
array<array<int, T>, T> &res) {
int i, j, k;
for (i = 0; i < T; ++i) {
for (j = 0; j < T; ++j) {
res[i][j] = 0;
}
}
for (i = 0; i < T; ++i) {
for (j = 0; j < T; ++j) {
for (k = 0; k < T; ++k) {
res[i][j] += a[i][k] * b[k][j];
}
}
}
}
int main() {
const int z = 3;
int n, i, j;
cout << "Enter number of 3x3 matrices: ";
cin >> n;
vector<array<array<int, z>, z> *> inp;
array<array<int, z>, z> mult;
for (int x = 0; x < n; x++) {
array<array<int, z>, z> *temp = new array<array<int, z>, z>;
cout << endl << "Enter elements of matrix " << x + 1 << ":" << endl;
for (i = 0; i < z; ++i) {
for (j = 0; j < z; ++j) {
cout << "Enter element (" << i << ", " << j << "): ";
cin >> (*temp)[i][j];
}
}
inp.push_back(temp);
}
mult = *inp[0];
for (int x = 1; x < n; x++) {
multMatrix(mult, *inp[x], mult);
}
// output
cout << endl << "Output Matrix: " << endl;
for (i = 0; i < z; ++i) {
for (j = 0; j < z; ++j)
cout << " " << mult[i][j];
cout << endl;
}
for (int x = 1; x < n; x++)
delete inp[x];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment