简体   繁体   English

如何在c ++中混合使用n个值的数组

[英]How to jumble up an array with n values in c++

I'm trying to make a function that mixes up the values of a given ordered array, say from 0 to n. 我正在尝试创建一个函数来混合给定有序数组的值,比如从0到n。 So this is my try: 所以这是我的尝试:

void JumbleUp(int *sorted,int n){
int jumble[n];
bool mark[n];
for(int i=0;i<n;i++)
    mark[i]=false;
int aux=0;
srand(time(NULL));
for(int i=0;i<n;i++){

    do {
        aux=(rand()%n);
        }while (mark[aux]);

    jumble[i]=sorted[aux];
    mark[aux]=true;
    }

The problem is that this function doesn't work for big integers because it takes a lot of time. 问题是这个函数不适用于大整数,因为它需要很多时间。 So what can I do to improve my function or what others alternatives can I use to jumble up an array. 那么我该怎么做才能改进我的功能,或者我可以使用其他替代品来混淆数组。

You are overthinking it. 你是在思考它。 First of all call srand only once when program starts. 首先在程序启动时调用srand一次。 Then for algorithm, something like pseudocode 然后是算法,像伪代码

for index in 0..n-1
    index2 = random (0..n-1)
    swap (ar, index, index2)

I could be wrong here, but I think it's important to get index2 in above range 0..n-1 and not for example index..n-1 , so every piece has equal chance to end up in all locations. 我可能在这里错了,但我认为将index2置于0..n-1以上范围并且不是例如index..n-1 ,因此每一件都有相同的机会在所有位置结束。 Alternative suggested in comment is this, which may also produce evenly distributed shuffle: 评论中建议的替代方案是这样,它也可以产生均匀分布的shuffle:

for index in 0..n-2
    index2 = random (index..n-1)
    swap (ar, index, index2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM