【问题标题】:Combinations in coin flipping掷硬币的组合
【发布时间】:2019-05-10 22:13:44
【问题描述】:

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

1) 用户输入他想要抛硬币的次数。

2) 程序必须根据用户输入返回所有可能的组合。

例子:

1 次抛硬币 --> 结果:HT

2 次抛硬币 --> 结果:HH HT TH TT

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 次抛硬币。

也许我需要改变解决问题的方法并应用递归,但我不知道怎么做。

你有什么建议吗?

谢谢。

【问题讨论】:

  • 请注意,如果您翻转 n 个硬币,您将获得 2^n 个组合。现在如果你把 H 变成 0 和 T 变成 1,那么你就有了从 0 到 n-1 的 2^n 个二进制数。
  • 想想汽车中的里程表是如何工作的可能会有所帮助——即最右边的刻度盘在每个时间步长都会增加,当它转回零时,它会将刻度盘推到它的位置。左前一格(依此类推)。然后将您的打印所有结果问题与制作里程表类似,除了在里程表上而不是每个表盘上的符号 0-9,您只需要符号 0-1(又名 H 和 T)。您可以创建一个 IncrementOdometer() 函数将里程表从当前状态移动到下一个状态,并创建一个 PrintOdometer() 函数打印当前状态并调用它们。

标签: c++ recursion combinations


【解决方案1】:

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 将您传递给构造函数的无符号转换为二进制表示。您可以将其转换为由chars 组成的std::string,然后传递给to_stringstd::bitsets 的大小在编译时是固定的,因此我使用了 32 位宽的 bitset,然后构造了一个子字符串来仅选择低位,以便您可以在运行时选择 n

Live Demo

【讨论】:

  • 谢谢。我并没有真正实现 bitset 类,但这个概念帮助我解决了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多