C++将数组的元素顺序随机打乱

参考:

https://blog.csdn.net/cordova/article/details/52884399

https://zhidao.baidu.com/question/1604258083773493627.html

自己的测试代码

 

    int array1[9] = {1,2,3,4,5,6,7,8,9};

    int array2[9] = { 0 };


    for (int i=8;i>0;i--)
    {
        int pos = rand() % i;
        printf("%d ", pos);

        array2[i] = array1[pos];

        for (int j = pos;j<8;j++)
        {
            array1[j] = array1[j+1];
        }
    }

    array2[0] = array1[0];

    printf("\n");
    for (int i = 0; i< 9 ; i++)
    {
        printf("%d ", array2[i]);
    }

 打乱之后,恢复:

#include<iostream>
using namespace std;
int main()
{
    char str[]="abcdefg123456789";
    char key[]="8635";
    char temp;
    /*利用秘钥乱序*/
    for(int j = 0; j < 2; j++)   //对于key的前两位
        for(int i = 0;(i+(key[j]-'0'))<=16; i++)
        {
                if(i%2!=0)//奇数位与其后面第key[j]位交换
                {
                temp = str[i+(key[j]-'0')];
                str[i+(key[j]-'0')] = str[i];
                str[i] = temp;
                }  
        }
    for(int i = 0; i < 16; i++)
        cout<<str[i]<<" ";
    cout<<endl;
    for(int j = 2; j < 4; j++)    //对于key的后两位
        for(int i = 0;(i+(key[j]-'0'))<=16; i++)
        {
            if(i%2==0)//偶数位与其后面第key[j]位交换
            {
                temp = str[i+(key[j]-'0')];
                str[i+(key[j]-'0')] = str[i];
                str[i] = temp;
                }  
        }
    for(int i = 0; i < 16; i++)
        cout<<str[i]<<" ";
    cout<<endl;
 
    /*利用秘钥复原*/
    for(int j = 3; j >= 2; j--)    //对于key的后两位
        for(int i = 16;(i-(key[j]-'0'))>=0; i--)
        {
            if(i%2!=0)//奇数位与其前面第key[j]位交换
            {
                temp = str[i-(key[j]-'0')];
                str[i-(key[j]-'0')] = str[i];
                str[i] = temp;
                }  
        }
    for(int i = 0; i < 16; i++)
        cout<<str[i]<<" ";
    cout<<endl;
 
    for(int j = 1; j >= 0; j--)   //对于key的前两位
        for(int i = 16;(i-(key[j]-'0'))>=0; i--)
        {
                if(i%2!=0)//奇数位与其前面第key[j]位交换
                {
                temp = str[i-(key[j]-'0')];
                str[i-(key[j]-'0')] = str[i];
                str[i] = temp;
                }  
        }
    for(int i = 0; i < 16; i++)
        cout<<str[i]<<" ";
    system("pause");
    return 0;
}

 

原文链接: https://www.cnblogs.com/zhangxuan/p/10438985.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++将数组的元素顺序随机打乱

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/290523

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午12:56
下一篇 2023年2月15日 下午12:57

相关推荐