Permutations

This is a discussion on Permutations within the C++ Programming forums, part of the General Programming Boards category; Hi, I am trying to write a program to generate permutations of an integer from 0 to a certain n(specified ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    84

    Permutations

    Hi,

    I am trying to write a program to generate permutations of an integer from 0 to a certain n(specified by the user).

    So for example -

    Code:
    n  = 1
    
    1
    
    n = 2
    
    1 2
    2 1
    
    n = 3
    
    1 2 3
    1 3 2
    2 1 3
    2 3 1
    3 1 2
    3 2 1
    and soo on...


    My program works works upto n = 3 but after that it starts repeating the output, here is a sample run from program -

    Code:
    1
    
    1
    
    2
    
    12
    21
    
    3
    
    123
    213
    231
    321
    312
    132
    
    4
    
    1234
    2134
    2314
    2341
    3241
    3421
    3412
    4312
    4132
    4123
    1423
    1243
    //REPEAT
    1234
    2134
    2314
    2341
    3241
    3421
    3412
    4312
    4132
    4123
    1423
    1243
    Here is my program, can someone let me know whats wrong ?

    Code:
    void GeneratePermutations(int input)
    {
    	int* arr = new int[input];
    	for(int i = 1; i <= input; ++i){
    		arr[i - 1] = i;
    	}
    	int lim = fact(input);
    	int counter = 1;
    	for(int i = 0; i < lim; ++i)
    	{		
    		for(int j = 0; j < input ; ++j)
    			cout << arr[j];			
    		cout << endl;
    		swap(arr[counter - 1],arr[counter]);
    		counter = (counter + 1) % input;	
    		if(counter == 0) counter = 1;
    	}
    }
    Thank you!

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,438
    so you mean when you put '5' in as your input it totally ignores it and outputs the results as if input was four?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. permutations
    By Kinshara in forum C Programming
    Replies: 10
    Last Post: 11-01-2009, 01:47 AM
  2. Permutations
    By bumfluff in forum C++ Programming
    Replies: 2
    Last Post: 10-05-2008, 12:33 PM
  3. permutations of a string
    By agarwaga in forum C Programming
    Replies: 1
    Last Post: 05-23-2006, 08:52 AM
  4. Permutations
    By mekaj in forum C++ Programming
    Replies: 5
    Last Post: 01-23-2006, 08:10 AM
  5. permutations
    By packer in forum C Programming
    Replies: 13
    Last Post: 06-02-2005, 12:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21