Porting Python algorithm to C++ - different solution
- by cb0
Hello,
I have written a little brute string generation script in python to generate all possible combinations of an alphabet within a given length. It works quite nice, but for the reason I wan't it to be faster I try to port it to C++.
The problem is that my C++ Code is creating far too much combination for one word.
Heres my example in python:
./test.py
gives me
aaa
aab
aac
aad
aa
aba
....
while ./test (the c++ programm gives me)
aaa
aaa
aaa
aaa
aa
Here I also get all possible combinations, but I get them twice ore more often.
Here is the Code for both programms:
#!/usr/bin/env python
import sys
#Brute String Generator
#Start it with ./brutestringer.py 4 6 "abcdefghijklmnopqrstuvwxyz1234567890" ""
#will produce all strings with length 4 to 6 and chars from a to z and numbers 0 to 9
def rec(w, p, baseString):
for c in "abcd":
if (p<w - 1):
rec(w, p + 1, baseString + "%c" % c)
print baseString
for b in range(3,4):
rec(b, 0, "")
And here the C++ Code
#include <iostream>
using namespace std;
string chars="abcd";
void rec(int w,int b,string p){
unsigned int i;
for(i=0;i<chars.size();i++){
if(b < (w-1)){
rec(w, (b+1), p+chars[i]);
}
cout << p << "\n";
}
}
int main ()
{
int a=3, b=0;
rec (a+1,b, "");
return 0;
}
Does anybody see my fault ? I don't have much experience with C++.
Thanks indeed