Code only prints last line to external file

I've been trying to get a code that will write permutations to an external file. I found a code online that does the permutations and outputs them all, but when I tried implementing a feature for it to output those permutations to an external file, only the last line goes through. Could anybody help me?



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

#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;

void printAllKLengthRec(char set[], string prefix, 
                                    int n, int k) 
{ 
    if (k == 0) 
    { 
        ofstream myfile;
        myfile.open ("example2.txt");     
        myfile << (prefix) << endl; 
        //cout << (prefix) << endl;     
        myfile.close();
        return; 
    } 
 
    for (int i = 0; i < n; i++) 
    {
        string newPrefix;  
    	  newPrefix = prefix + set[i];  
        printAllKLengthRec(set, newPrefix, n, k - 1);
    } 
  
} 
  
void printAllKLength(char set[], int k,int n) 
{ 
    printAllKLengthRec(set, "", n, k); 
} 
  

int main () {
  
  
  char set2[] = {'a', 'b', 'c', 'd'}; 
    int k = 2; 
    printAllKLength(set2, k, 4);
  return 0;
}
You're opening and closing the file over and over and overwriting it each time. Although you could open it in append mode and therefore append each line, it's more efficient to open the file in main and pass it to the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
using namespace std;

void printAllKLength(ostream& out, char set[], int k, int n, string prefix="") {
    if (k == 0)
        out << prefix << '\n';
    else
        for (int i = 0; i < n; i++)
            printAllKLength(out, set, k - 1, n, prefix + set[i]);
}

int main() {
    char set2[] = "abcd";
    ofstream out("example2.txt");
    printAllKLength(out, set2, 2, 4); // or you can pass cout instead
}

Those aren't actually permutations, BTW.
Thank you so much! It finally works! And what do you meant that they aren't permutations?
Permutations are rearrangements of the elements, so there shouldn't be duplicates unless the original set has duplicates.

So permutations of 1, 2, 3 are

123
132
213
231
312
321


C++ has next_permutation for this task:

1
2
3
4
5
6
7
8
9
10
11
#include <algorithm>
#include <iostream>
#include <string>

int main() {
    std::string s{"123"};
    std::sort(s.begin(), s.end()); // ensure that it's sorted (not needed here)
    do
        std::cout << s << '\n';
    while (std::next_permutation(s.begin(), s.end()));
}

Last edited on
So what would you call a repeating permutation, for lack of a better term?
I guess they are permutations since you consider "ab" and "ba" to be different. It could maybe be called "permutations of 4 objects taken 2 at a time with duplicates" (or "with replacement") which is unusual.
Topic archived. No new replies allowed.