无重复的随机数组生成

Random array generation with no duplicates(无重复的随机数组生成)

本文介绍了无重复的随机数组生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些可以生成没有重复值的随机数组的东西.我已经看过其他答案,但似乎没有一个能帮助我理解.我想不出一种方法来实际生成不包含重复项的随机数.这是我迄今为止尝试过的:

srand(time(NULL));整数 [4];for (int x=0; x!=4;x++){数字[x] = 1 + (rand() % 4) ;printf("%d", 数字[x]);}

<块引用>

任何帮助将不胜感激.

解决方案

首先rand() 是生成随机数,但不能重复.

如果您想生成一个没有重复项的随机数组,rand() 方法根本不起作用.

假设您要生成一个1000个数字的数组.在最好的情况下,假设您生成了没有重复的前 999 个数字,最后想做的是生成最后一个数字.获得这个数字的概率是 1/1000,所以这几乎需要很长时间才能生成.实际上,只有 10 个数字会带来很大的麻烦.

最好的方法是通过增量(或严格单调序列)生成所有数字,即混洗它们.在这种情况下,将没有重复

这里 是一个关于如何使用 10 个数字的示例.即使有 1000 个号码,它也工作.

注意:来自 Jhon Leehey 的 答案.

#include #include #include void shuffle(int *arr, size_t n){如果 (n > 1){size_t i;srand(时间(空));for (i = 0; i 

I am trying to create something that generates a random array with no duplicate values. I've already looked at other answers but none seem to help me understand. I cannot think of a way to actually generate random numbers that contain no duplicates. Here is what i have tried so far:

srand(time(NULL));
int numbers [4];

for (int x=0; x!=4;x++)
{
    numbers[x] = 1 + (rand() % 4) ;
    printf("%d ", numbers[x]);
}

Any help will be appreciated.

解决方案

First of all rand() is generatig random numbers but not wihout duplicates.

If you want to generate a random array without duplicates the rand() method is not working at all.

Let say you want to generate an array of 1000 numbers. In the best case let say you generated the first 999 numbers without duplicates and last think to do is generating the last number. The probability of getting that number is 1/1000 so this is almost going to take forever to get generated. In practice only 10 numbers makes a big trouble.

The best method is to generate all your numbers by incrementation (or strictly monotonic sequence) is shuffle them. In this case there will be no duplicates

Here is an exemple on how to do it with 10 numbers. Even with 1000 numbers it's working.

Note: Suffle function from Jhon Leehey's answer.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void shuffle(int *arr, size_t n)
{
    if (n > 1) 
    {
        size_t i;
        srand(time(NULL));
        for (i = 0; i < n - 1; i++) 
        {
          size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
          int t = arr[j];
          arr[j] = arr[i];
          arr[i] = t;
        }
    }
}

int main()
{
    int i;
    int arr[10];
    for (i=0; i<10; i++){
        arr[i] = i;
    }
    shuffle(arr, 10);
    for (i=0; i<10; i++){
        printf("%d ", arr[i]);
    }
}

这篇关于无重复的随机数组生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无重复的随机数组生成

基础教程推荐