谢谢大家的帮助。在这篇文章的下面,我把这两个脚本的正确版本,现在产生相等的输出。将Python算法移植到C++ - 不同的解决方案
你好,
我已经写了一个小畜生串生成脚本在python给定长度内产生一个字母的所有可能的组合。它工作的很好,但因为我不想更快,所以我尝试将它移植到C++。
问题是我的C++代码为一个单词创建了太多的组合。 我的继承人在Python的例子:
./test.py
给我
aaa aab aac aad aa aba ....
而./test
(C++的PROGRAMM给我)
aaa aaa aaa aaa aa
在这里,我还可以得到所有可能的组合,但我经常给他们两次矿石。
下面是两个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, "")
而且这里的C++代码
#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;
}
是否有人看到我的错吗?我对C++没有多少经验。
由于确实
这里修正版本:
C++
#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)){
rec(w, (b+1), p+chars[i]);
}
}
cout << p << "\n";
}
int main()
{
rec (3,0, "");
return 0;
}
的Python
#!/usr/bin/env python
import sys
def rec(w, b, p):
for c in "abcd":
if (b < w - 1):
rec(w, b + 1, p + "%c" % c)
print p
rec(4, 0, "")
相等的输出:
$ ./test > 1
$ ./test.py 3 3 "abcd" "" > 2
$ diff 1 2
$
谢谢,我没有注意到蟒蛇也被打破了。 而且输出也是错位的:( 它应该只打印一次而不是每次迭代(谢谢) – cb0 2010-04-14 15:20:02