斯巴达手杖问题C++解决

//密钥在于 加密面数+起始位置 
//整个加解密过程是 根据明/密文填写矩阵,
//再按照相应的规律读出密(逆时针横向)/明文 (纵向读) 
//以下示例明文为:dhaeibfcg
//               密文为:abcdefghi
//               面数为:4 
//        起始位置为:2
//  0 1 2 3  
//0   a b c    
//1 d e f g
//2 h i

#include<iostream>
#include<bits/stdc++.h> 
using namespace std;
void encrypt(char* plaintext,int key1,int key2){//加密 
    int length=strlen(plaintext);
    int inum=ceil( (length+key2-1)/(float)key1 );//矩阵空间的行数 
    int jnum=key1;//矩阵空间的列数 
    vector<vector<char> > res(inum, vector<char>(jnum, '.'));//动态创建矩阵空间并初始化 
    int k0=0;
    for(int j=0;j<jnum&&k0<length;j++)
    {
        for(int i= j<(key2-1)?1:0;i<(j<( (length+key2-2)%key1+1)?inum:inum-1)&&k0<length;i++)
        {    
            res[i][j]=plaintext[k0++];
        }
     } 
    
    //按规律读取的密文 
    cout<<"The ciphertext is:";
    for(auto temp:res) {
        for(auto i:temp) {
            //cout<<i;
            if(i!='.')
            cout<<i;
        }
        //cout<<endl;
    }
}

void decrypt(char* ciphertext,int key1,int key2){//解密 
    int length=strlen(ciphertext);
    int inum=ceil( (length+key2-1)/(float)key1 );//矩阵空间的行数 
    int jnum=key1;//矩阵空间的列数 
    vector<vector<char> > res(inum, vector<char>(jnum, '.'));//动态创建矩阵空间并初始化 
    int k0=0;
    for(int i=0;i<inum&&k0<length;i++)
    {
        for(int j= i==0?key2-1:0;j<jnum&&k0<length;j++)
        {    
        
            res[i][j]=ciphertext[k0++];
        }
     } 
    
//    for(auto temp:res) {
//        for(auto i:temp) {
//            cout<<i;
//        }
//        cout<<endl;
//    }
    //按规律读取的明文 
    cout<<"The plaintext is:";
    for(int j=0;j<jnum;j++)
    {
        for(int i=0;i<inum;i++)
        {
        if(res[i][j]!='.')
            cout<<res[i][j];
        }    
    }
    
     
}

int main()
{
    char plaintext[100];
    char ciphertext[100];
    int key1;
    int key2; 
    cout<<"choose the function"<<endl<<"1.encrypt"<<endl<<"2.decrypt"<<endl;
    int choice;
    cin>>choice;
    if(choice==1)
    {
        cout<<"please input the plaintext:";
        cin>>plaintext;
         
        cout<<"please input the surfacenum:";
        cin>>key1;
        cout<<"please input the startposition:";
        cin>>key2;
        encrypt(plaintext,key1,key2); 
    }
    if(choice==2)
    {
        cout<<"please input the ciphertext:";
        cin>>ciphertext;
        
        cout<<"please input the surfacenum:";
        cin>>key1;
        cout<<"please input the startposition:";
        cin>>key2;
        decrypt(ciphertext,key1,key2);
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值