我正在尝试为家庭作业加密邮件

I'm trying to encrypt a message for my homework assignment

本文关键字:家庭作业 加密      更新时间:2023-10-16

它的要点是来自a-z的每个字母都需要加密成一个数字。

例如,a将变为"1",b变为"2",一直到z="26"。然后,我必须猜测每个加密的可能结果的数量。例如,25114可以是6个不同的东西。它可以是BEAN,BEAAD,YAAD,YAN,YKD,BEKD。

我的问题是"我该怎么做"? 我尝试使用if但它每次都打印"1"作为输出。

#include <iostream>
using namespace std;
int main()
{
int a1,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;
cout<<"vnesi kod"<<endl;
cin>>a1;
if (a)
{
cout<<"1"<<endl;
}
else if (b)
{
cout<<"2"endl;
}
return 0;
}

由于这是一个家庭作业问题,我只是给你一些关于如何解决这个问题的伪代码。您仍然必须自己实现它。

让我们假设您从n位数字中得到一个数字作为输入:a 1 a 2a3...n

由于字母表包含 26 个字母,我们希望将此数字分成 1 位或 2 位数字的组,如果我们有一组两位数,则必须检查该数字是否小于 27。最快的方法是使用递归函数。它不是最干净的,而是最快的。让我们假设递归函数称为decode

很容易理解为什么需要递归函数。如果我们想解码数字25114。我们需要采取两条路径,1 组和 2 组:

  • 1组:将最后一个数字4转换为"D",解码剩余的数字2511
  • 2组:检查最后两位数字是否小于27,将最后两位数字14转换为N,解码剩余数字251

在伪代码中,这看起来像这样:

# function decode
#   input: the number n to decode
#          a postfix string p representing the decoded part
function decode(n, p) {
# end condition: If the number is ZERO, I have decoded the full number
#                only print and return
if (n == 0) { print p; return }
# group of 1: use integer division to extract the
#             last digit as n%10 and
#             remainder to decode is n/10
decode(n/10, concat(translate(n%10),p) )
# group of 2: use integer division to extract the
#             last two digits as n%100 and
#             remainder to decode is n/100
# This does not need to run if n < 10 or if n%100 > 26
if (n > 9 && n%100 <= 26) { decode(n/100, concat(translate(n%100),p) ) }
}
  • 函数concat连接两个字符串:concat("AA","BB")返回"AABB"
  • 该函数translate(n)将数字n转换为其相应的字母字符。这可以写成sprintf("%c",64+n)

正如评论中提到的,这不是一种非常有效的方法。这是因为我们一遍又一遍地做同样的工作。如果输入为25114,我们将按顺序执行以下步骤:

step 1: translate(4), decode _2511_
step 1.1: translate(1), decode _251_
step 1.1.1: ...
step 1.2: translate(11), decode _25_
step 1.2.1: ...
step 2: translate(14), decode _251_

如您所见,我们必须对251进行两次解码(在步骤 1.1 和步骤 2 中(。这是非常低效的,因为我们做任何事情都比做更多。

为了改善这一点,您可以在查找表中跟踪到目前为止所做的工作

查看 ASCII 表 http://www.asciitable.com/。我的家庭作业也有类似的东西。由于"a"= 97 且"z"= 122,因此您可以从 96 中减去所需的字符,以从转换字符中获取首选值。

例如:

int letterNum {(int)'a' - 97 + 1}; // 1
int letterNum {(int)'z' - 97 + 1}; // 26