最初,代码输出组合而无需替换。它可以在Combination without replacement C++处找到。我添加了在集合完成时从集合中减去一个的部分。例如,如果输入集合{0,1,2,3,4}中的4的组合,则输出将如下:
梳子(N =从中选择的项目,K =设定量)
梳子(N = 5,K = 4) 〜输出〜0,1,2,3
0,1,2,4
0,1,3,4
0,2,3,4
1,2,3,4
⇓ 梳子(N = 5,K = 4-1) 〜输出〜
0,1,2
0,1,3
0,1,4
0,2,3
0,2,4
0,3,4
1,2,3
1,2,4
1,3,4
2,3,4
⇓ 梳子(N = 5,K =(4-2)或(3-1)) 〜输出〜
0,1
0,2
0,3
0,4
1,2
1,3
1,4
2,3
2,4
3,4
⇓ 梳子(5,K =(4-3)或(2-1)) 〜输出〜 END
如果想要将数字更改为具有相同顺序的数字的字母,那么如何使用模数进行此操作?关于如何做到这一点的任何其他想法?
我的尝试如下。
#include <iostream>
#include <string>
using namespace std;
void comb(int N, int K)
{
std::string bitmask(K, 1);
bitmask.resize(N, 0);
do {
for (int i = 0; i < N; ++i)
{
if (bitmask[i])
std::cout << " " << i;
if (i == 0 || i%10 == 0)
std::cout << " " << "C" << endl;
else if (i == 1 || i%10 == 1)
std::cout << " " << "C#" << endl;
else if (i == 2 || i%10 ==1)
std::cout << " " << "D" << endl;
//the "else if" statements go up to i == 11 which is B//
}
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
int main()
{
for (int i = 6; i > 0; i--){
comb(6,i);
}
}
输出效果不尽如人意。
Sound
0C
1C#
2D
3D#
Sound
0C
1C#
2D
D#
0C
1C#
2D
D#
0C
...
答案 0 :(得分:1)
嗯,将0
到n
整数映射到另一种类型的经典方法是使用数组。
const std::string string_map[] =
{
"C", // instead of 0
"C#", // instead of 1
"D", // instead of 2
....
}
然后在相同的代码中,使用n
...
string_map[n]