参考:
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; }