C/C++ 将数据乱序

来源:互联网 发布:低碳钢的弹性模量算法 编辑:程序博客网 时间:2024/06/05 04:36

我们在实现某些应用或者做测试的时候,需要将某些数据乱序。例如1,2,3三个数,随机乱序后,可能是2,1,3。

最简单的方法是:输入一系列数,顺序访问每个位置的数,将当前位置的数与一个随机数相关的位置进行内容交换


纯C实现

#include <stdio.h>#include <stdlib.h>#include <inttypes.h>// n : the length of an arrayint rand_id(int n){     return rand() % n;}// data : 1-D // size_ele : size of per element// len : the length of datavoid rand_perm(uint8_t* data, uint8_t size_ele, int len, int (*rand_id)(int)){    int i, j, idx;    uint8_t *cptr = data;    uint8_t *tmp = (uint8_t*)malloc(size_ele);    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;    }    free(tmp); tmp = 0;}#define __N 4int main(int argc, char** argv){    // test int    int32_t a[__N] = {10000000,20000000,30000000,40000000};    rand_perm((uint8_t*)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((uint8_t*)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((uint8_t*)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 200000000.000001 0.000002 0.000004 0.0000030.000002 0.000004 0.000003 0.000001 

纯C++

C++标准里有随机洗牌函数,我们可以直接调用。

#include <iostream>#include <algorithm>using namespace std;#define __N 4int 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 300000000.000004 0.000001 0.000003 0.0000020.000003 0.000001 0.000004 0.000002
0 0
原创粉丝点击