473,385 Members | 1,888 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Find all Permutations of a list

I need to find all the possible permutations of a list and I am completely stumped. The specification for the function is:
Expand|Select|Wrap|Line Numbers
  1. void allPerms(intListType *toOrigList, intListType *answer)
  2.  
where *toOrigList is a pointer to a list and *answer is an array of lists. intListType has several member functions and I will post them if you want them, but for the most part they are barely used in this function (which is not a member function). I'm having trouble outputting the permutations because the program keeps crashing. I cannot change the specification of the function and if you want the rest of the program I will post it. Anyway, here is what I have of the function so far:

Expand|Select|Wrap|Line Numbers
  1. #include "allPerms.h"
  2. #include <string>
  3. #include <cstddef>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. void allPerms(intListType *toOrigList, intListType *answer)
  8. //Pre: list is not empty
  9. //Post: computes all permutations of a given list
  10. {
  11.     int length = toOrigList->getLength();
  12.  
  13.     if(length == 1){
  14.         toOrigList->copyTo(&answer[0]);
  15.     }
  16.     else{
  17.         toOrigList->resetList();
  18.  
  19.         for(int i = 0; i < length; i++){
  20.             intListType smallerList;
  21.             int amount = factorial(length-1);
  22.             intListType array[amount];
  23.             int first = toOrigList->getNextInt();
  24.  
  25.             toOrigList->copyTo(&smallerList);
  26.             smallerList.deleteInt(first);
  27.             allPerms(&smallerList, array);
  28.  
  29.             for(int j = 0; j < amount; j++){
  30.                 array[].copyTo(&answer[]);
  31.             }
  32.         }
  33.     }
  34. }
  35.  
  36. int factorial(int n)
  37. //Pre: enter integer
  38. //Post: returns factorial of number
  39. {
  40.     int answer;
  41.  
  42.     if(n < 0){
  43.         throw string("no factorial for numbers less than 0");
  44.     }
  45.     else if(n == 0){
  46.         answer = 1;
  47.     }
  48.     else{
  49.         answer = n*factorial(n-1);
  50.     }
  51.  
  52.     return answer;
  53. }
  54.  
Thank you for any help you may be able to provide!
Apr 3 '12 #1
9 3396
array[].copyTo(&answer[]);<----the arrays are empty because I don't know what to put in them to get it to work properly
Apr 3 '12 #2
weaknessforcats
9,208 Expert Mod 8TB
First, you are dealing with permutations rather than combinations. So each permutation is an ordered variation of the original set. Like 4321 is a permutation of 1234 but 432 is not.

That said, this code:
Expand|Select|Wrap|Line Numbers
  1. intListType array[amount];
requires intListType to have a cnstructor to initialize the array. But each element of the array musy be allocated enought memory to hold a permutation. This implies intListType knows the number of elements in the permutation. This will be hard to do with no argument for it.

Also this code:
Expand|Select|Wrap|Line Numbers
  1. intListType array[amount];
shows allocation on the stack. Stack memory is limited an this sort of thing can cause a crash.You should do all of your allocations on the heap using the "new" operator.

There are n! permutations of a set. So your answers can be in an array of n! elements provided each element is allocated (on the heap) a size equal to the size of the original set. You need to do this before copying stuff around.
Apr 3 '12 #3
So you're saying that I should make all the arrays like this?
Expand|Select|Wrap|Line Numbers
  1. intListType array = new intListType[amount];
  2.  
Also, do you want me to post my intListType class or the constructor for it?
Apr 3 '12 #4
weaknessforcats
9,208 Expert Mod 8TB
Yes, you should do that but also each element of array will hold a permutation so you need to allocate memory for each element. Since i don't have your code look at this:

1) assume my permutation set is 10 integers.
2) So I need an aray of 10! elements where each element is itself an array of 10 int.
3) 10! is 3,628,800

Expand|Select|Wrap|Line Numbers
  1. int (*array)[10] = new int[3628800][10];
Now array[0] is an array of 10 int and array[0] can hold one permutation.

In this scheme individual elements of the permutation would be
array[0][i] where i varies from 0 to 9.

Of course, since this is C++ you should be using vector since vector is implemented as an array. However, I didn't want to muddy the water with refinements when the code is not yet working.

For more info on how this array is allocated read: http://bytes.com/topic/c/insights/77...rrays-revealed
Apr 3 '12 #5
First off, very nice article I wish I knew about that when I was learning multidimensional arrays. Secondly, I'm getting confused because I'm new to programming and very new to using recursion. I'm trying to make variables to do what you suggested and I can't because I'm having trouble tracking what my code is doing. Right now I gave my array constant values, but I don't think that works do to the nature of my program. If I have: (using a list of 1,2,3)
Expand|Select|Wrap|Line Numbers
  1. intListType (*array)[3] = new intListType[6][3];
I get a compile error. Here is my code so you can give me a more concrete example/directions if you're up to it. I appreciate your help and thank you if you feel like reading through all this.

intList.h
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. using namespace std;
  3.  
  4. struct nodeType;
  5.  
  6. class intListType
  7. {
  8.     public:
  9.         intListType();
  10.         int getLength();
  11.         void putInt(int x);
  12.             //Pre: x is not already in list
  13.             //Post: insert x at the head of the list
  14.         void resetList();
  15.             //PostL set current location to be off the end of the list
  16.         int getNextInt();
  17.             //Pre: list has not been changed since last reset
  18.             //     current location is not the end of the list
  19.             //Post: advance current location and return int at next location
  20.         void deleteInt(int x);
  21.             //Pre: x is on the list
  22.             //Post: delete x
  23.         bool isIn(int x);
  24.             //Pre: list was initialized
  25.             //Post: returns true or false if x in list
  26.         void copyTo(intListType *toNew);
  27.         string toString();
  28.         ~intListType();
  29.             //Post: free up the memory used by the list
  30.             //      and set the header of the list to NULL
  31.     private:
  32.         nodeType* listHead;
  33.         nodeType* currentLocation;
  34.             //points to a node in the list, or NULL if off the end of the list
  35.         int length;
  36. };
  37.  
intList.cpp
Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include "intList.h"
  3. #include <cstddef>
  4. #include <sstream>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. struct nodeType
  10. {
  11.     int info;
  12.     nodeType* next;
  13. };
  14.  
  15. intListType::intListType()
  16. {
  17.     length = 0;
  18.     listHead = NULL;
  19.     currentLocation = NULL;
  20. }
  21.  
  22. int intListType::getLength()
  23. {
  24.     return length;
  25. }
  26.  
  27. void intListType::putInt(int x)
  28.     //Pre: x is not already in list
  29.     //Post: insert x at the head of the list
  30. {
  31.     nodeType* toLocation;
  32.     toLocation = new nodeType;
  33.     (*toLocation).info = x;
  34.     (*toLocation).next = listHead;
  35.     listHead = toLocation;
  36.     length = length + 1;
  37. }
  38.  
  39. void intListType::resetList()
  40.     //PostL set current location to be off the end of the list
  41. {
  42.     currentLocation = NULL;
  43. }
  44.  
  45. int intListType::getNextInt()
  46.     //Pre: list has not been changed since last reset
  47.     //     current location is not the end of the list
  48.     //Post: advance current location and return int at next location
  49. {
  50.     if(currentLocation == NULL){
  51.         currentLocation = listHead;
  52.     }
  53.     else{
  54.          currentLocation = currentLocation->next;
  55.         if(currentLocation == NULL){
  56.             throw string("Attempt to getNextInt when next is the last entry in last");
  57.         }
  58.     }
  59.     return (*currentLocation).info;
  60. }
  61.  
  62.  
  63. void intListType::deleteInt(int x)
  64.     //Pre: x is on the list
  65.     //Post: delete x
  66. {
  67.     nodeType *prevNode = listHead;
  68.     currentLocation = listHead->next;
  69.  
  70.     if(x == listHead->info){
  71.         nodeType *oldNode = listHead;
  72.         listHead = listHead->next;
  73.         delete oldNode;
  74.     }
  75.     else{
  76.         while(!(currentLocation->info == x)){
  77.             prevNode = currentLocation;
  78.             currentLocation = currentLocation->next;
  79.             if(currentLocation == NULL){
  80.                 throw string("Item to be deleted was not found");
  81.             }
  82.         }
  83.         nodeType *nodeToDel;
  84.         nodeToDel = currentLocation;
  85.         prevNode->next = currentLocation->next;
  86.     }
  87.     length--;
  88. }
  89.  
  90. bool isInRec(nodeType *toHead, int x); //declaration
  91. bool intListType::isIn(int x)
  92. {
  93.     return isInRec(listHead, x);
  94. }
  95. bool isInRec(nodeType *toHead, int x)
  96. {
  97.     bool answer;
  98.  
  99.     if(toHead == NULL){
  100.         answer = false;
  101.     }
  102.     else if(toHead->info == x){
  103.         answer = true;
  104.     }
  105.     else{
  106.         answer = isInRec(toHead->next, x);
  107.     }
  108.  
  109.     return answer;
  110. }
  111.  
  112. string toStringRec(nodeType *toNode); //declaration
  113. string intListType::toString()
  114. {
  115.     return toStringRec(listHead);
  116. }
  117. string toStringRec(nodeType *toNode)
  118. {
  119.     stringstream s;
  120.     if(toNode != NULL){
  121.         s << toNode->info << '\t';
  122.         s << toStringRec(toNode->next);
  123.     }
  124.     return s.str();
  125. }
  126.  
  127. void copyToRec(intListType *toNew, nodeType *toHead);
  128. void intListType::copyTo(intListType *toNew)
  129. {
  130.     copyToRec(toNew, listHead);
  131. }
  132. void copyToRec(intListType *toNew, nodeType *toHead)
  133. {
  134.     if(toHead != NULL){
  135.         toNew->putInt(toHead->info);
  136.         copyToRec(toNew, toHead->next);
  137.     }
  138. }
  139.  
  140.  
  141. void destroyRec(nodeType *toNode);
  142. intListType::~intListType()
  143. {
  144.     destroyRec(listHead);
  145. }
  146. void destroyRec(nodeType *toNode)
  147. {
  148.     if(toNode == NULL){
  149.         //do nothing
  150.     }
  151.     else{
  152.         destroyRec(toNode->next);
  153.         delete toNode;
  154.     }
  155. }
  156.  
allPerms.h
Expand|Select|Wrap|Line Numbers
  1. #include "intList.h"
  2.  
  3. void allPerms(intListType *toOrigList, intListType *answer);
  4. //Pre: list is not empty
  5. //Post: computes all permutations of a given list
  6.  
  7. int factorial(int n);
  8. //Pre: enter integer
  9. //Post: returns factorial of number
  10.  
allPerms.cpp
Expand|Select|Wrap|Line Numbers
  1. #include "allPerms.h"
  2. #include <string>
  3. #include <cstddef>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. void allPerms(intListType *toOrigList, intListType *answer)
  8. //Pre: list is not empty
  9. //Post: computes all permutations of a given list
  10. {
  11. //    int length = toOrigList->getLength();
  12. //
  13. //    if(length == 1){
  14. //        toOrigList->copyTo(&answer[0]);
  15. //    }
  16. //    else{
  17. //        toOrigList->resetList();
  18. //
  19. //        for(int i = 0; i < length; i++){
  20. //            intListType smallerList;
  21. //            int amount = factorial(length-1);
  22. //            intListType array[amount];
  23. //            int first = toOrigList->getNextInt();
  24. //
  25. //            toOrigList->copyTo(&smallerList);
  26. //            smallerList.deleteInt(first);
  27. //            allPerms(&smallerList, array);
  28. //
  29. //            for(int j = 0; j < amount; j++){
  30. //                array[].copyTo(&answer[]);
  31. //            }
  32. //        }
  33. //    }
  34.     int length = toOrigList->getLength();
  35.  
  36.     if(length == 1){
  37.         toOrigList->copyTo(&answer[0]);
  38.     }
  39.     else{
  40.         toOrigList->resetList();
  41.  
  42.         for(int i = 0; i < length; i++){
  43.             intListType smallerList;
  44.             int amount = factorial(length-1);
  45.             intListType (*array)[6] = new intListType[3][6];
  46.             int first = toOrigList->getNextInt();
  47.  
  48.             toOrigList->copyTo(&smallerList);
  49.             smallerList.deleteInt(first);
  50.             allPerms(&smallerList, array);
  51.  
  52.             for(int j = 0; j < amount; j++){
  53.                 array[i][j].copyTo(&answer[i]);
  54.             }
  55.         }
  56.     }
  57. }
  58.  
  59. int factorial(int n)
  60. //Pre: enter integer
  61. //Post: returns factorial of number
  62. {
  63.     int answer;
  64.  
  65.     if(n < 0){
  66.         throw string("no factorial for numbers less than 0");
  67.     }
  68.     else if(n == 0){
  69.         answer = 1;
  70.     }
  71.     else{
  72.         answer = n*factorial(n-1);
  73.     }
  74.  
  75.     return answer;
  76. }
  77.  
allPermsDr.cpp
Expand|Select|Wrap|Line Numbers
  1. #include "allPerms.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. void guts()
  6. {
  7.     int n;
  8.     cout << "Enter a positive integer: ";
  9.     cin >> n;
  10.     cout << endl;
  11.  
  12.     intListType aList;
  13.     aList.resetList();
  14.     for(int i = 1; i <= n; i++){
  15.         aList.putInt(i);
  16.     }
  17.  
  18.     intListType *allPermutations;
  19.     int f = factorial(n);
  20.     allPermutations = new intListType[f];
  21.     allPerms(&aList, allPermutations);
  22.  
  23.     for(int p = 0; p < f; p++){
  24.         cout << (allPermutations[p]).toString() << endl;
  25.     }
  26. }
  27.  
  28. int main()
  29. {
  30.     try{
  31.         guts();
  32.     }catch(string message){
  33.         cout << "Exception thrown: " << message << endl;
  34.     }
  35. }
  36.  
Thank you
Apr 3 '12 #6
weaknessforcats
9,208 Expert Mod 8TB
Your code compiles for me on Visual Studio.NET 2008.

But I had to make one change: You are missing a semicolon at the end of the struct nodeType definition.

Plus in C++ to define an array of class intListType objects you need both a default constructor and a destructor. I used your default ctor but had to code a dtor.
Apr 3 '12 #7
Wait so with those changes, if you inputted 3 it would output:
123
213
312
and so on?
I know they program can compile without any errors, but when it runs I'm fairly confident its getting a segmentation fault or something like that because it just crashes (my compiler doesn't tell me)
Apr 4 '12 #8
weaknessforcats
9,208 Expert Mod 8TB
This would be an excellent time to start using your debugger and stepping through the code.

Use a small permutaion set, like 3 so there are few permutations.

As you step through be sure all your variables contain the expected values.

Nothing "just crashes" and your debugger will lead to right to the problem.

As to the set 123, the permutations are:

123
213
231
321
132
312

There are 3! permutations.
Apr 4 '12 #9
ok Thank you very much
Apr 5 '12 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

10
by: Steve Goldman | last post by:
Hi, I am trying to come up with a way to develop all n-length permutations of a given list of values. The short function below seems to work, but I can't help thinking there's a better way. ...
20
by: John Trunek | last post by:
I have a set of X items, but want permutations of length Y (X > Y). I am aware of the permutation functions in <algorithm>, but I don't believe this will do what I want. Is there a way, either...
11
by: Girish Sahani | last post by:
Hi guys, I want to generate all permutations of a string. I've managed to generate all cyclic permutations. Please help :) def permute(string): l= l.append(string) string1 = '' for i in...
20
by: anurag | last post by:
hey can anyone help me in writing a code in c (function) that prints all permutations of a string.please help
7
by: Christian Meesters | last post by:
Hi, I'd like to hack a function which returns all possible permutations as lists (or tuples) of two from a given list. So far, I came up with this solution, but it turned out to be too slow for...
1
by: JosAH | last post by:
Greetings, last week we talked a bit about generating permutations and I told you that this week will be about combinations. Not true; there's a bit more to tell about permutations and that's...
5
by: Shraddha | last post by:
Suppose we are having 3 variables...a,b,c And we want to print the permutations of these variables...Such as...abc,acb,bca...all 6 of them... But we are not supposed to do it mannually... I...
2
by: Assimalyst | last post by:
Hi I have a Dictionary<string, List<string>>, which i have successfully filled. My problem is I need to create a filter expression using all possible permutations of its contents. i.e. the...
82
by: Bill Cunningham | last post by:
I don't know if I'll need pointers for this or not. I wants numbers 10^16. Like a credit card 16 digits of possible 10 numbers, so I guess that would be 10^16. So I have int num ; These are of...
2
by: alemo91 | last post by:
Write a recursive function to print all possible permutations of a given string. For example if the input string is “abc” then the set of permutations is: abc, acb, bac, bca, cab, cba. Hint:...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.