C++ Массив случайных не повторяюшихся чисел (легкий апгоритм)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//http://www.cyberforum.ru/c-beginners/thread44753.html
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ARR_SIZE 10240
void gen_random_uniq2( int arr_size, int *parr, int range_min, int range_max );
* ================================================================ */
int main( int argc, char *argv[] ) {
int i, arr_size;
int arr[MAX_ARR_SIZE];
int range_min, range_max;
srand( time( NULL ) );
if ( argc!=1+3 ) {
fprintf( stderr, "Usage: gen_random_uniq2 arr_size range_min range_max\n" ); exit( 1 );
}
arr_size= atoi( argv[1] );
range_min= atoi( argv[2] );
range_max= atoi( argv[3] );
if ( arr_size<0 || arr_size>MAX_ARR_SIZE ) {
fprintf( stderr, "Invalid array size\n" ); exit( 1 );
}
gen_random_uniq2( arr_size, arr, range_min, range_max );
printf( "random unique array: array size is %d, range is [%d;%d]\n",
arr_size, range_min, range_max
);
for ( i= 0; i<arr_size; i++ ) {
printf( " %d", arr[i] );
}
printf( "\n" );
return 0;
} /* main() */
* ================================================================ */
void gen_random_uniq2( int arr_size, int *parr, int range_min, int range_max ) {
int i, arr2_size, index, range_width;
int *parr2= NULL;
/* Check arguments */
range_width= range_max-range_min+1;
if ( range_width<1 || arr_size<0 || arr_size>range_width ) {
fprintf( stderr, "gen_random_uniq2(): Invalid arguments\n" ); exit( 1 );
}
if ( arr_size == 0 ) { return; }
/* Alloc */
parr2= (int*)malloc( range_width*sizeof(int) );
if ( parr2 == NULL ) {
fprintf( stderr, "gen_random_uniq2(): No enough memory\n" ); exit( 1 );
}
/* Init */
for ( i= 0; i<range_width; i++ ) {
parr2[i]= range_min+i;
}
/* Loop */
arr2_size= range_width;
for ( i= 0; i<arr_size; i++ ) {
index= rand()%arr2_size;
parr[i]= parr2[index];
arr2_size--;
parr2[index]= parr2[arr2_size];
}
/* Free */
if ( parr2 != NULL ) { free( parr2 ); parr2= NULL; }
} /* gen_random_uniq2() */