ActiveState Code

Recipe 576566: Permutations.cpp


Made this program for a friend who needed a quick way to print out permutations of words, and how many their were. This does exactly that, and outputs it to a file.

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
*
  Coded by: LogicKills;
       For: logickills.org;
    Reason: Someone asked for help;
    
    Notes: All it does it write to permutations.txt
           Doesn't check for existence, or error.
           Overwrites permutations from older execution.
           Made this in about 5 min :]
           
*/

#include <iostream>
#include <algorithm>
#include <string>
#include <fstream>

using std::string;   using std::cout;
using std::endl;     using std::cin;
using std::ofstream;


int main(int argc, char *argv[])
{
    
	if (argc != 2)
       {     
             cout << "\nUsage: prm [ word ]  " << endl;
             cout << "  \nNote: " << endl;
             cout << " permutations.txt will be saved in the same dir that the prm.exe is in." << endl;
            
             return 1;
       }

      
    string x = argv[1];
    int z = 1;
    

    
    ofstream outFile;
    outFile.open("permutations.txt");
    outFile << "Permutations of the word " << x << endl;
    sort(x.begin(),x.end());
    outFile << x << std::endl;
    while(next_permutation(x.begin(), x.end()))
    {
           outFile << x << endl;
           z++;
    }
    outFile << "Total number of permutations: " << z << endl;
         

  return 0;
}

Sign in to comment