c++ - 抛硬币的组合

标签 c++ recursion combinations

我正在尝试编写一个计算抛硬币组合的小程序:

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_stringchar 组成的 std::stringstd::bitset 的大小在编译时是固定的,因此我使用了一个 32 位宽的 bitset,然后构造一个子字符串来只选择较低的位,这样你就可以选择 n 在运行时。

Live Demo

关于c++ - 抛硬币的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56085422/

相关文章:

c++ - 用C++、EWS通过exchange服务器发送邮件

python - 辅助函数与主函数同名吗?

ruby - Ruby 中数组哈希的所有可能组合

c++ - 编译扩展名为.c的CPP程序

c++ - 字符串 vector 的高效组合

database-design - RethinkDB 分层数据

javascript - 需要帮助才能获得尽可能多的独特啤酒

生成 n 个项目的 k 元组的算法,每个项目至少使用一次 (k>n)

c++ - SDL 绘图程序卡住

java - 我使用递归按字母顺序获取第一个字符串的 java 代码给出了不正确的输出。我需要添加辅助方法吗?