gpt4 book ai didi

language-agnostic - 确定具有非唯一选择的无序组合数量的函数

转载 作者:行者123 更新时间:2023-12-01 17:31:24 25 4
gpt4 key购买 nike

我正在尝试确定用于确定具有非唯一选择的无序组合数量的函数。

给定:

n = number of unique symbols to select from
r = number of choices

示例...对于 n=3,r=3,结果将是:(编辑:添加 Dav 指出的缺失值)

000
001
002
011
012
022
111
112
122
222

我知道排列的公式(无序、唯一的选择),但我无法弄清楚允许重复如何增加集合。

最佳答案

在 C++ 中给出以下例程:

template <typename Iterator>
bool next_combination(const Iterator first, Iterator k, const Iterator last)
{
/* Credits: Mark Nelson http://marknelson.us */
if ((first == last) || (first == k) || (last == k))
return false;
Iterator i1 = first;
Iterator i2 = last;
++i1;
if (last == i1)
return false;
i1 = last;
--i1;
i1 = k;
--i2;
while (first != i1)
{
if (*--i1 < *i2)
{
Iterator j = k;
while (!(*i1 < *j)) ++j;
std::iter_swap(i1,j);
++i1;
++j;
i2 = k;
std::rotate(i1,j,last);
while (last != j)
{
++j;
++i2;
}
std::rotate(k,i2,last);
return true;
}
}
std::rotate(first,k,last);
return false;
}

然后您可以继续执行以下操作:

std::string s = "12345";
std::size_t r = 3;
do
{
std::cout << std::string(s.begin(),s.begin() + r) << std::endl;
}
while(next_combination(s.begin(), s.begin() + r, s.end()));

关于language-agnostic - 确定具有非唯一选择的无序组合数量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1960147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com