随机打乱一组数(出题)

 1 /*
 2 打乱一组数据a[0]~a[n-1]:
 3 给出0~n-1的编号,打乱这些编号,得到编号数组b[0]~b[n-1],
 4 现在的数据为a[b[0]],a[b[1]],…,a[b[n-1]]
 5 */
 6 #include <cstdio>
 7 #include <cstdlib>
 8 #include <cstring>
 9 #include <cmath>
10 #include <string>
11 #include <set>
12 #include <map>
13 #include <list>
14 #include <queue>
15 #include <vector>
16 #include <algorithm>
17 using namespace std;
18 const long n=100; //1e6
19 const long max_int=1<<15;//long 1<<15 ; unsigned long 1<<16
20 const long X=n/max_int+(n%max_int!=0);
21 const long Y=n%max_int;
22 
23 long a[n],x,y;
24 
25 int main()
26 {
27     FILE* fp=fopen("data.txt","w");
28     long i,j,index,t;
29     for (i=0;i<n;i++)
30         a[i]=i;
31     srand(0);
32     //每次确定a[i]的数值,index的数值是随机的,因而a[i]的数值也是随机的
33     //O(n)
34     for (i=n-1;i>=0;i--)
35     {
36         //分成两部分 v=max_int*x+y x=0..X-1 y=0..Y-1
37         index=floor(1.0*rand()/max_int*X) *max_int + floor(1.0*rand()/max_int*Y);
38         t=a[index];
39         a[index]=a[i];
40         a[i]=t;
41     }
42     for (i=0;i<n;i++)
43         fprintf(fp,"%ld ",a[i]);
44     fclose(fp);
45     return 0;
46 }

thanks for the help of a classmate

原文地址:https://www.cnblogs.com/cmyg/p/8965558.html