/*---------------------------------------------------------------------------
File name: main.cpp
Author: HJin
6/15/2007 01:17:45
This is the problem of repeatable permutation, which needs basic
knowledge about recursive function calls.
The required 256 permutations are written in a.txt.
Sample output from Repeatable_Permutation( int )
1 0000
2 0001
3 0010
4 0011
5 0100
6 0101
7 0110
8 0111
9 1000
10 1001
11 1010
12 1011
13 1100
14 1101
15 1110
16 1111
Press any key to continue . . .
*/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string s; // a global buffer
/**
Output to a ASCII file.
*/
void Repeatable_Permutation(int n, ofstream& ofs);
/**
Output to stdout.
*/
void Repeatable_Permutation(int n);
int main()
{
int n=4;
Repeatable_Permutation(n);
ofstream ofs("a.txt");
if(!ofs)
{
cout<<"cannot create a file\n";
exit(0);
}
n=8;
s=""; // clear s
Repeatable_Permutation(n, ofs);
ofs.close();
return 0;
}
void Repeatable_Permutation(int n, ofstream& ofs)
{
string temp;
if(n==0)
{
ofs<<s<<endl;
return;
}
else
{
temp = s; // remember the previous state of s
// write 0 and repeat n-1 times
s+="0";
Repeatable_Permutation(n-1, ofs);
// write 1 and repeat n-1 times
s = temp; // restore the previous state
s+="1"; // write 1
Repeatable_Permutation(n-1, ofs);
}
}
void Repeatable_Permutation(int n)
{
static int count=0; // counter
string temp;
if(n==0)
{
++count;
cout<<count<<"\t"<<s<<endl;
return;
}
else
{
temp = s;
s+="0";
Repeatable_Permutation(n-1);
s = temp;
s+="1";
Repeatable_Permutation(n-1);
}
}