我正在尝试编写一个计算抛硬币组合的小程序:
1) 用户输入他想掷多少次硬币。
2) 程序必须根据用户输入返回所有可能的组合。
例子:
1次抛硬币-->结果:HT
2次抛硬币-->结果:HH HT TH TT
throw 3 次硬币 --> 结果:HHH HHT HTH HTT THH THT TTH TTT
ECC...
我在 C++ 中尝试过这种方法:
#include <iostream>
#include <string>
using namespace std;
// function that returns the coin face using the indexes used in for loops below
string getCoinFace(int index) {
if(index == 0)
return "H";
return "T";
}
int main() {
string result = "";
// 3 nested loops because I toss the coin 3 times
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
result += getCoinFace(i) + getCoinFace(j) + getCoinFace(k) + '\n';
}
}
}
cout << result;
/* --OUTPUT--
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT
*/
return 0;
}
这仅在执行 3 次抛硬币时有效,但我需要改为处理 N 次抛硬币。
也许我需要改变解决问题的方法并应用递归,但我不知道该怎么做。
你有什么建议吗?
谢谢。
最佳答案
std::bitset
几乎是微不足道的:
#include <iostream>
#include <bitset>
int main() {
const unsigned max_n = 32;
unsigned n = 3;
unsigned combos = 1 << n;
for (unsigned i=0;i<combos;++i)
std::cout << std::bitset<max_n>(i).to_string('H','T').substr(max_n-n,n) << "\n";
}
简而言之,std::bitset
将您传递给构造函数的无符号数转换为二进制表示形式。您可以将其转换为由传递给 to_string
的 char
组成的 std::string
。 std::bitset
的大小在编译时是固定的,因此我使用了一个 32 位宽的 bitset
,然后构造一个子字符串来只选择较低的位,这样你就可以选择 n
在运行时。
关于c++ - 抛硬币的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085422/