Skip to content

Instantly share code, notes, and snippets.

@Mohamed-Ibrahim-01
Last active May 20, 2022 01:07
Show Gist options
  • Save Mohamed-Ibrahim-01/53b90b2eed126c57748068f43ad17b6a to your computer and use it in GitHub Desktop.
Save Mohamed-Ibrahim-01/53b90b2eed126c57748068f43ad17b6a to your computer and use it in GitHub Desktop.
matrix_flatten.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
* Returning the index in the flatten matrix for n by m by p matrix.
*
* @param n dimention 1 of 3d matrix
* @param m dimention 2 of 3d matrix
* @param p dimention 3 of 3d matrix
*
* @return vector<int> vector of size q the size of the flatten matrix.
*/
vector<int> create_flatten_vector(int n, int m, int p){
long q = 1L*n*m*p;
return vector<int>(q);
}
/*
* Returning the index in the flatten matrix for n by m by p matrix.
*
* @param n dimention 1 of 3d matrix
* @param m dimention 2 of 3d matrix
* @param p dimention 3 of 3d matrix
*
* @param i index 0 of 3d matrix
* @param j index 1 of 3d matrix
* @param k index 2 of 3d matrix
*
* @return y index in the flatten matrix
* */
long get_flatten_idx(int n, int m, int p, int i, int j, int k){
vector<int> input {n, m, p, i, j, k};
if(any_of(input.begin(), input.end(), [](int x){ return x < 0; })){
return -1;
}
long y = (1L*i*m*p) + (j*p) + (k);
return y;
}
int main() {
vector<vector<vector<int>>> matrix3D {
{ {1, 2}, {3, 4} },
{ {4, 5}, {6, 7} },
{ {8, 9}, {10, 11} }
};
int n = matrix3D.size(), m = matrix3D[0].size(), p = matrix3D[0][0].size();
vector<int> flatten = create_flatten_vector(n, m, p);
for(int i = 0; i < matrix3D.size(); i++){
for(int j = 0; j < matrix3D[i].size(); j++){
for(int k = 0; k < matrix3D[i][j].size(); k++){
long y = get_flatten_idx(n, m, p, i, j, k);
flatten[y] = matrix3D[i][j][k];
}
}
}
for(int x : flatten){
cout << x << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment