#include <vector> #include <iostream> using namespace std; vector<int> insert(co
ID: 3599650 • Letter: #
Question
#include <vector> #include <iostream> using namespace std; vector<int> insert(const vector<int> & prev, int pos, int elem){ vector<int> v; for (int i=0; i<pos; i++) v.push_back(prev[i]); v.push_back(elem); for (int i=pos; i<prev.size();i++) v.push_back(prev[i]); return v; } vector<vector<int> > getPermutationssOfOneToN(int n){ vector<vector<int> > v; vector<int> s; if (n<=0){ v.push_back(s); return v; } else{ vector<vector<int> > v2 = getPermutationssOfOneToN(n-1); // all permutations of {1 .. n-1} for (int i=0; i<v2.size(); i++){ s = v[i]; // s is one permutation of {1 ... n-1} for (int j=0; j<=s.size(); j++){ vector<int> new_perm = insert(s,j,n); v.push_back(new_perm); } } return v; } } void print_vector(const vector<int>& v){ for (int i=0; i<v.size(); i++) cout << v[i] << " "; cout << endl; } int main(){ for (int i= 1; i<5; i++){ cout << "permutationss of {1.." << i << "}:" << endl; vector<vector<int> > perms = getPermutationssOfOneToN(i); for (vector<vector<int> >::iterator itr=perms.begin(); itr<perms.end(); itr++) print_vector(*itr); } } I want the output look like this. g++ -o get_all_permutations.o get_all_permutations.cpp ./get_all_permutations.o permutationss of {1..1}: 1 permutationss of {1..2}: 2 1 1 2 permutationss of {1..3}: 3 2 1 2 3 1 2 1 3 3 1 2 1 3 2 1 2 3 permutationss of {1..4}: 4 3 2 1 3 4 2 1 3 2 4 1 3 2 1 4 4 2 3 1 2 4 3 1 2 3 4 1 2 3 1 4 4 2 1 3 2 4 1 3 2 1 4 3 2 1 3 4 4 3 1 2 3 4 1 2 3 1 4 2 3 1 2 4 4 1 3 2 1 4 3 2 1 3 4 2 1 3 2 4 4 1 2 3 1 4 2 3 1 2 4 3 1 2 3 4
Explanation / Answer
Rather than doing this, you could use the std::next_permutation on a sorted number to get all the permutations -
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main() {
int number[4]; //suppose you want permutation of 1 till 4
cin>>number;
int lengthOfTheNumber = strlen(number);
sort(anagrama, number+lengthOfTheNumber );
do {
cout << number << endl;
} while (next_permutation(number, number+lengthOfTheNumber));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.