参考:
https://blog.csdn.net/cordova/article/details/52884399
https://zhidao.baidu.com/question/1604258083773493627.html
自己的测试代码
int array1[] = {,,,,,,,,}; int array2[] = { }; for (int i=;i>;i--)
{
int pos = rand() % i;
printf("%d ", pos); array2[i] = array1[pos]; for (int j = pos;j<;j++)
{
array1[j] = array1[j+];
}
} array2[] = array1[]; printf("\n");
for (int i = ; i< ; i++)
{
printf("%d ", array2[i]);
}
打乱之后,恢复:
#include<iostream>
using namespace std;
int main()
{
char str[]="abcdefg123456789";
char key[]="";
char temp;
/*利用秘钥乱序*/
for(int j = ; j < ; j++) //对于key的前两位
for(int i = ;(i+(key[j]-''))<=; i++)
{
if(i%!=)//奇数位与其后面第key[j]位交换
{
temp = str[i+(key[j]-'')];
str[i+(key[j]-'')] = str[i];
str[i] = temp;
}
}
for(int i = ; i < ; i++)
cout<<str[i]<<" ";
cout<<endl;
for(int j = ; j < ; j++) //对于key的后两位
for(int i = ;(i+(key[j]-''))<=; i++)
{
if(i%==)//偶数位与其后面第key[j]位交换
{
temp = str[i+(key[j]-'')];
str[i+(key[j]-'')] = str[i];
str[i] = temp;
}
}
for(int i = ; i < ; i++)
cout<<str[i]<<" ";
cout<<endl; /*利用秘钥复原*/
for(int j = ; j >= ; j--) //对于key的后两位
for(int i = ;(i-(key[j]-''))>=; i--)
{
if(i%!=)//奇数位与其前面第key[j]位交换
{
temp = str[i-(key[j]-'')];
str[i-(key[j]-'')] = str[i];
str[i] = temp;
}
}
for(int i = ; i < ; i++)
cout<<str[i]<<" ";
cout<<endl; for(int j = ; j >= ; j--) //对于key的前两位
for(int i = ;(i-(key[j]-''))>=; i--)
{
if(i%!=)//奇数位与其前面第key[j]位交换
{
temp = str[i-(key[j]-'')];
str[i-(key[j]-'')] = str[i];
str[i] = temp;
}
}
for(int i = ; i < ; i++)
cout<<str[i]<<" ";
system("pause");
return ;
}