|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <time.h> |
| 4 | + |
| 5 | +int *generateUniqueRandIntegers(int min, int max, int count) |
| 6 | +{ |
| 7 | + if (count > (max - min + 1)) |
| 8 | + { |
| 9 | + printf("Error: Cannot generate more unique random numbers than the range allows.\n"); |
| 10 | + return NULL; |
| 11 | + } |
| 12 | + |
| 13 | + if (min > max) |
| 14 | + { |
| 15 | + printf("Error: Invalid range.\n"); |
| 16 | + return NULL; |
| 17 | + } |
| 18 | + |
| 19 | + int rangeSize = max - min + 1; |
| 20 | + int *numbers = malloc(rangeSize * sizeof(int)); |
| 21 | + if (numbers == NULL) |
| 22 | + { |
| 23 | + printf("Error: Memory allocation failed.\n"); |
| 24 | + return NULL; |
| 25 | + } |
| 26 | + |
| 27 | + // Initialize the array |
| 28 | + for (int i = 0; i < rangeSize; i++) |
| 29 | + { |
| 30 | + numbers[i] = min + i; |
| 31 | + } |
| 32 | + |
| 33 | + // Shuffle the array using Fisher-Yates algorithm |
| 34 | + srand(time(NULL)); |
| 35 | + for (int i = rangeSize - 1; i > 0; i--) |
| 36 | + { |
| 37 | + int j = rand() % (i + 1); |
| 38 | + int temp = numbers[i]; |
| 39 | + numbers[i] = numbers[j]; |
| 40 | + numbers[j] = temp; |
| 41 | + } |
| 42 | + |
| 43 | + // Create a new array to store the selected unique random numbers |
| 44 | + int *selectedNumbers = malloc(count * sizeof(int)); |
| 45 | + if (selectedNumbers == NULL) |
| 46 | + { |
| 47 | + printf("Error: Memory allocation failed.\n"); |
| 48 | + free(numbers); |
| 49 | + return NULL; |
| 50 | + } |
| 51 | + |
| 52 | + // Copy the first 'count' elements from the shuffled array to the selectedNumbers array |
| 53 | + for (int i = 0; i < count; i++) |
| 54 | + { |
| 55 | + selectedNumbers[i] = numbers[i]; |
| 56 | + } |
| 57 | + |
| 58 | + free(numbers); |
| 59 | + return selectedNumbers; |
| 60 | +} |
| 61 | + |
| 62 | +int main() |
| 63 | +{ |
| 64 | + int min = 1; // Minimum value |
| 65 | + int max = 1000000; // Maximum value |
| 66 | + int count = 50000; // Number of unique random numbers to generate |
| 67 | + |
| 68 | + int *randomArray = generateUniqueRandIntegers(min, max, count); |
| 69 | + if (randomArray != NULL) |
| 70 | + { |
| 71 | + printf("Generated unique random numbers:\n"); |
| 72 | + for (int i = 0; i < count; i++) |
| 73 | + { |
| 74 | + printf("%d\n", randomArray[i]); |
| 75 | + } |
| 76 | + free(randomArray); |
| 77 | + } |
| 78 | + |
| 79 | + return 0; |
| 80 | +} |
0 commit comments