問題描述
我正在嘗試創建一些可以生成沒有重復值的隨機數組的東西.我已經看過其他答案,但似乎沒有一個能幫助我理解.我想不出一種方法來實際生成不包含重復項的隨機數.這是我迄今為止嘗試過的:
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]);
}
}
這篇關于無重復的隨機數組生成的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!