如何生成两种硬币的所有可能组合,具有三种可能性(上,下和中间)

时间:2016-07-21 03:58:40

标签: c# python c++ matlab cartesian-product

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

$exploded = explode('-', '2016-1-1');
$exploded[0] -= 1;
print_r(implode('-', $exploded));

// Output:
// 2015-1-1

其中,.gitignore表示头(向上), 00 01 10 11 表示尾(向下)。

以下是打印先前组合的代码:

0

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

1

其中, for n=1:2^2 r(n) = dec2bin(n); end 表示两个硬币中的一个介于两者之间(不是向上或向下)

任何想法?

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

我找到了几种MATLAB解决方案。 (那不完全是我的代码,我发现了一些部分并对其进行了调整)。发布它是因为@C.Colden' answer未满。 你想要达到的是permutations with repetitions。 C.Colden没有重复地显示它。所以你可以这样:

解决方案1:

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

答案 4 :(得分:0)

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

这只是一个简单的双嵌套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