我们在实现某些应用或者做测试的时候,需要将某些数据乱序。例如1,2,3三个数,随机乱序后,可能是2,1,3。
最简单的方法是:输入一系列数,顺序访问每个位置的数,将当前位置的数与一个随机数相关的位置进行内容交换。
#include <stdio.h>
#include <stdlib.h>
// n : the length of an array
int rand_id(int n){
return rand() % n;
}
// data : 1-D
// size_ele : size of per element
// len : the length of data
void rand_perm(char* data, int size_ele, int len, int (*rand_id)(int)){
int i, j, idx;
char *cptr = data;
char tmp[16];
for (i = 0; i < len; i++){
idx = rand_id(len);
for (j = 0; j < size_ele; j++){
tmp[j] = data[idx*size_ele + j];
}
for (j = 0; j < size_ele; j++){
data[idx*size_ele + j] = cptr[j];
}
for (j = 0; j < size_ele; j++){
cptr[j] = tmp[j];
}
cptr += size_ele;
}
}
#define __N 4
int main(int argc, char** argv){
// test int
int a[__N] = {10000000,20000000,30000000,40000000};
rand_perm((char*)a, sizeof(a[0]), __N, rand_id);
for (int i = 0; i < __N; i++){
printf("%d ", a[i]);
}
printf("\n");
// test float
float b[__N] = {1.E-6f, 2.E-6f, 3.E-6f, 4.E-6f};
rand_perm((char*)b, sizeof(b[0]), __N, rand_id);
for (int i = 0; i < __N; i++){
printf("%f ", b[i]);
}
printf("\n");
// test double
double c[__N] = { 1.E-6, 2.E-6, 3.E-6, 4.E-6 };
rand_perm((char*)c, sizeof(c[0]), __N, rand_id);
for (int i = 0; i < __N; i++){
printf("%f ", c[i]);
}
printf("\n");
return 0;
}
输出结果
10000000 40000000 30000000 20000000 0.000001 0.000002 0.000004 0.000003 0.000002 0.000004 0.000003 0.000001
C++标准里有随机洗牌函数,我们可以直接调用。
#include <iostream>
#include <algorithm>
using namespace std;
#define __N 4
int main(int argc, char** argv){
// test int
int a[__N] = { 10000000, 20000000, 30000000, 40000000 };
std::random_shuffle(a, a + __N);
for (int i = 0; i < __N; i++){
cout << a[i] << " ";
}
cout << endl;
// test float
float b[__N] = { 1.E-6f, 2.E-6f, 3.E-6f, 4.E-6f };
std::random_shuffle(b, b + __N);
for (int i = 0; i < __N; i++){
cout << std::fixed << b[i] << " ";
}
cout << endl;
// test double
double c[__N] = { 1.E-6, 2.E-6, 3.E-6, 4.E-6 };
std::random_shuffle(c, c + __N);
for (int i = 0; i < __N; i++){
cout << std::fixed << c[i] << " ";
}
cout << endl;
return EXIT_SUCCESS;
}
输出结果
10000000 20000000 40000000 30000000 0.000004 0.000001 0.000003 0.000002 0.000003 0.000001 0.000004 0.000002