問題描述
我正在嘗試創(chuàng)建一些可以生成沒有重復(fù)值的隨機(jī)數(shù)組的東西.我已經(jīng)看過其他答案,但似乎沒有一個(gè)能幫助我理解.我想不出一種方法來實(shí)際生成不包含重復(fù)項(xiàng)的隨機(jī)數(shù).這是我迄今為止嘗試過的:
srand(time(NULL));整數(shù) [4];for (int x=0; x!=4;x++){數(shù)字[x] = 1 + (rand() % 4) ;printf("%d", 數(shù)字[x]);}
<塊引用>
任何幫助將不勝感激.
首先rand()
是生成隨機(jī)數(shù),但不能重復(fù).
如果您想生成一個(gè)沒有重復(fù)項(xiàng)的隨機(jī)數(shù)組,rand()
方法根本不起作用.
假設(shè)您要生成一個(gè)1000個(gè)數(shù)字的數(shù)組.在最好的情況下,假設(shè)您生成了沒有重復(fù)的前 999 個(gè)數(shù)字,最后想做的是生成最后一個(gè)數(shù)字.獲得這個(gè)數(shù)字的概率是 1/1000,所以這幾乎需要很長時(shí)間才能生成.實(shí)際上,只有 10 個(gè)數(shù)字會(huì)帶來很大的麻煩.
最好的方法是通過增量(或嚴(yán)格單調(diào)序列)生成所有數(shù)字,即混洗它們.在這種情況下,將沒有重復(fù)
這里 是一個(gè)關(guān)于如何使用 10 個(gè)數(shù)字的示例.即使有 1000 個(gè)號(hào)碼,它也工作.
注意:來自 Jhon Leehey 的 答案.
#include #include #include void shuffle(int *arr, size_t n){如果 (n > 1){size_t i;srand(時(shí)間(空));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]);
}
}
這篇關(guān)于無重復(fù)的隨機(jī)數(shù)組生成的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!