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
//http://www.cyberforum.ru/c-beginners/thread44753.html
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ARR_SIZE 1024
void gen_random_uniq( 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_uniq 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_uniq( 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_uniq( int arr_size, int *parr, int range_min, int range_max ) {
int i, j;
int dup_flag;
int rand_val, range_width= range_max-range_min+1;
if ( range_width<1 || arr_size<0 || arr_size>range_width ) {
fprintf( stderr, "gen_random_uniq(): Invalid arguments\n" ); exit( 1 );
}
for ( i= 0; i<arr_size; i++ ) {
for ( ; ; ) {
rand_val= range_min+rand()%range_width;
dup_flag= 0;
for ( j= 0; j<i; j++ ) {
if ( rand_val == parr[j] ) { dup_flag= 1; break; }
}
if ( !dup_flag ) { break; }
}
parr[i]= rand_val;
}
}
} /* gen_random_uniq() */