c++ - Displaying Matrix elements in Strange Order -
i not sure order of printing called hence called strange.
consider following sample example:
1 3 5 2 6 7
expected output:
1,2 1,6 1,7 3,2 3,6 3,7 5,2 5,6 5,7
or example:
1 2 3 4 5 6 7 8 9
output:
1,4,7 1,4,8 1,4,9 1,5,7 1,5,8 1,5,9 ... , on.
i have analyzed number of possible combinations rows^columns
given matrix.here solution:
#include <iostream> #include <vector> #include <string> #include <cstdlib> #include <cstdio> using namespace std; void printallpossiblecombinations(int** a, int h, int n, string prefix) { if (h == 0) { (int = 0; < n; i++) { cout << prefix << a[0][i] << endl; } } else { (int = 0; < n; i++) { string recursivestring = prefix; recursivestring.append(to_string(a[h][i])); recursivestring.append(1, ','); printallpossiblecombinations(a, h-1, n, recursivestring); } } } int main() { int **a; int m,n,k; cout<<"enter number of rows: "; cin>>m; = new int*[m]; cout<<endl<<"enter number of columns: "; cin>>n; for(int i=0;i<m;i++) { a[i] = new int [n]; } for(int i=0;i<m;i++) { for(int j = 0; j < n;j++) { cout<<"enter a[" << << "][" << j<< "] = "; cin>>a[i][j]; cout<<endl; } } printallpossiblecombinations(a, m-1, n, ""); return 0; }
is there easy , more optimized way of doing it? please suggest.
thank you
as said, there rows^columns
things physically print out in algorithm can't better o(rows^columns)
algorithm , algorithm optimal you'll get.
Comments
Post a Comment