如何生成具有三种可能性(向上、向下和介于两者之间)的两种硬币的所有可能组合

How to generate all possible combinations of two coins with three possibilities (up, down and In between)

给定两个硬币,结果的数量将为 2^2(两个硬币只有两种可能性(正面(向上)或尾部(向下))。给出以下可能的组合:

 00   
 01
 10
 11

其中,0表示头(上),1表示尾(下)。

这里是打印前面组合的代码:

 for n=1:2^2
 r(n) = dec2bin(n);
 end

我想要做的是打印相同两个硬币的所有可能组合,但具有三种不同的可能性(正面(向上)、尾部(向下)和中间(不是向上或向下)) 给出类似的东西:

00
01
10
11
0B
B0
B1
1B
BB

其中,B表示两个硬币之一在中间(不是向上或向下)

有什么想法吗?

Python 解决方案:

from itertools import product

possible_values = '01B'
number_of_coins = 2

for result in product(possible_values, repeat=number_of_coins):
    print(''.join(result))

# Output:
# 00
# 01
# 0B
# 10
# 11
# 1B
# B0
# B1
# BB
from itertools import product

outcomes = ["".join(item) for item in list(product('01B', repeat=2))]
for outcome in outcomes:
    print(outcome)
#reusults:
00
01
0B
10
11
1B
B0
B1
BB

Matlab解决方案: n 是可能的解决方案的数量。在你的情况下 3 一次不同。 k是套数。在你的情况下 2 个硬币。 p应该包含一个带有结果的矩阵。

n = 3; k = 2;
nk = nchoosek(1:n,k);
p=zeros(0,k);
for i=1:size(nk,1),
    pi = perms(nk(i,:));
    p = unique([p; pi],'rows');
end

更多解决方案请查看:Possible combinations - order is important

我找到了几个 MATLAB 的解决方案。 (这不完全是我的代码,我找到了一些部分并对其进行了调整)。 Post 因为 未满。 你要实现的是一个permutations with repetitions。 C.Colden 不重复显示。所以你可以这样走:

解决方案一:

a = [1 2 3]
n = length(a)
k = 2
for ii = k:-1:1
    temp = repmat(a,n^(k-ii),n^(ii-1));
    res(:,ii) = temp(:);
end

结果:

res =

 1     1
 1     2
 1     3
 2     1
 2     2
 2     3
 3     1
 3     2
 3     3

有趣的解决方案 2 如果您需要它的字符串形式:

dset={'12b','12b'};
n=numel(dset);
pt=[3:n,1,2];
r=cell(n,1);
[r{1:n}]=ndgrid(dset{:});
r=permute([r{:}],pt);
r=sortrows(reshape(r,[],n));

结果:

r =

11
12
1b
21
22
2b
b1
b2
bb

虽然我不熟悉这些其他语言的语法,但它们的解决方案看起来过于复杂。

这只是一个简单的双重嵌套 for 循环:

C++

#include <iostream>
using namespace std;

int main() 
{
    const char* ch = "01B";
    for (int i = 0; i < 3; ++i)
    {
        for (int j = 0; j < 3; ++j)
            cout << ch[i] << ch[j] << '\n';
    }
}

输出:

00
01
0B
10
11
1B
B0
B1
BB

在 C++ 中

#include<iostream>
using namespace std;
int main(){
    string s="HT";
for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
        for(int k=0;k<2;k++){
            cout<<s[i]<<s[j]<<s[k]<<endl;
        }
    }
}


}