如何在这个程序中使用模数将数字变为字母?

How does one change a number to letter using a modulus in this program?

本文关键字:数字 程序      更新时间:2023-10-16

原来,代码输出组合而不替换。它可以在没有替换的组合中找到。c++ I添加了当集合完成时从集合中减去1的部分。例如,如果输入集合{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))~输出~

结束

如果一个人想把数字变成字母,而数字的顺序是相同的,那么如何用模数来做到这一点呢?关于如何做到这一点,还有其他的想法吗?

我的尝试如下。

#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
...

0n的整数映射到另一种类型的经典方法是使用数组。

const std::string string_map[] =
{
    "C",  // instead of 0
    "C#", // instead of 1
    "D",  // instead of 2
    ....
}

然后在同一代码中,用string_map[n]代替整数n