seanohue
500+ Head-Fier
- Joined
- Jan 11, 2006
- Posts
- 755
- Likes
- 10
I'm doing recursion now in my C++ class and I am stuck with my code. I'm trying to write a program that will compute all the permutations for a number. Say I enter 4, which gives me 24 permutations of 1234 since 4! = 24. My code thus far is this:
Code:
What I am attempting to do is create a large vector (supervec) of integer vectors (vints). After each permutation, the rearranged vint is stored in an index of the supervec. My problem is getting the swap to work. I can't figure out how to rearrange the numbers inside the vector and get it to work recursively. That mess of code in the permutations function doesn't work, the only thing that does it the base case. Can anyone point me in the right direction? (well, more like give me a big kick in the rear) I'm stumped at this point.
Code:
Code:
[left]#include <iostream> #include <vector> using namespace std; typedef vector<int> vint; int factorial(int n) { if(n == 0) return 1; int smaller_factorial = factorial(n - 1); int result = smaller_factorial * n; return result; } vector<vint> permutations(int permute) { int vec_size = factorial(permute); vector<vint> supervec(vec_size); vint vec(permute); if(permute == 1) { vec[0] = 1; supervec[0] = vec; return supervec; } else for(int j = 1; j == permute; j++) { vec[j - 1] = j; } for(int i = 0; i < supervec.size(); i++) { for(int k = 0; k < vec.size(); k++) { for(int n = ; n < ; n++) { vector<int> remain(vec.size() - k - 1); remain[n] = vec[ } for(int m = (vec.size() - 1); n < (vec.size() - k - 1); n++) { vec[vec.size() - k - m] = remain[vec.size() - k - m]; } } supervec[i] = vec; } return supervec; } int main() { cout << "Enter the an integer (not 0)\n"; int x; cin >> x; vector<vint> vec = permutations(x); vector<int> tempvec; for(int i = 0; i < vec.size(); i++) { vec[i] = tempvec; for(int j = 0; j < tempvec.size(); j++) { cout << tempvec[j] << "\n"; } } return 0; }[/left]
What I am attempting to do is create a large vector (supervec) of integer vectors (vints). After each permutation, the rearranged vint is stored in an index of the supervec. My problem is getting the swap to work. I can't figure out how to rearrange the numbers inside the vector and get it to work recursively. That mess of code in the permutations function doesn't work, the only thing that does it the base case. Can anyone point me in the right direction? (well, more like give me a big kick in the rear) I'm stumped at this point.