如何创建一个数组的随机排列?

编程入门 行业动态 更新时间:2024-10-26 18:15:28
本文介绍了如何创建一个数组的随机排列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我用C编写的这个功能,我想它来创建一个随机排列或数字从1到n的列表。我无法得到它没有重复号码。所以,如果你有N = 4,我想它返回一个包含各1-4只进行一次随机序列,例如:{1,3,4,2}

为int *随机(INT N){    为int * R =的malloc(N * sizeof的(INT));    //号的初始范围    的for(int i = 0; I< N ++我){         - [R [i] = I + 1;    }    //洗牌    的for(int i = 1; I< = N; ++ I){        INT J =兰特()%I;         - [R [i] = R [J]。         - [R [J] =我;  }  返回ř;}

解决方案

更改您的第二个为循环:

的for(int i = N-1; I> = 0; --i){    //生成一个随机数[0,N-1]    INT J =兰特()%(I + 1);    //交换最后一个元素与元素随机指数    INT温度= R [I]     - [R [i] = R [J]。     - [R [J] =温度;}

这是一个费雪耶茨洗牌算法。我一直在使用听说兰特()%N 不均匀分布,你已经被警告。

如果你想每次生成唯一的排列,可以存储生成的排列,可能在词典或的Hashmap ,然后查找每次你回来。我不认为 C 有一个内置的之一,但应该有可用的库。

I've written this function in C and I want it to create a random permutation or a list of numbers from 1 to n. I'm having trouble getting it to have no repeating numbers. So if you have n = 4, i would like it to return a random array containing 1-4 each only once, for example: {1,3,4,2}

int* random(int n) { int* r = malloc(n * sizeof(int)); // initial range of numbers for(int i=0;i<n;++i){ r[i]=i+1; } // shuffle for (int i = 1; i <= n; ++i){ int j = rand() % i; r[i] = r[j]; r[j] = i; } return r; }

解决方案

Change your second for loop to:

for (int i = n-1; i >= 0; --i){ //generate a random number [0, n-1] int j = rand() % (i+1); //swap the last element with element at random index int temp = r[i]; r[i] = r[j]; r[j] = temp; }

This is a Fisher-Yates shuffling algorithm. I have heard using rand() % n doesn't distribute uniformly, you've been warned.

And if you want to generate unique permutations everytime, you can store the generated permutations, maybe in a Dictionary or Hashmap, and then lookup everytime you return. I don't think C has a built in one but there should be libraries available.

更多推荐

如何创建一个数组的随机排列?

本文发布于:2023-11-30 10:07:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649604.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   创建一个   排列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!