How to generate N combinations of X random numbers between min and max in C

1 Answer

0 votes
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
 
#define SIZE 7
   
int getRandom(int min, int max) {
    return (rand() % (max - min + 1)) + min; 
}
  
void GenerateNRandomNumbers(int N, int array[], int min, int max) {
    for (int i = 0; i < N; i++) {
        array[i] = getRandom(min, max);
    }
}
 
void printCombination(int array[], int size, int combinations, int resi, int result[], int arri) {
    if (resi == combinations) {
        for (int j = 0; j < combinations; j++) {
            printf("%d ", result[j]);
        }
        printf("\n");
        return;
    }
 
    if (arri >= size) {
        return;
    }
 
    result[resi] = array[arri];
    printCombination(array, size, combinations, resi + 1, result, arri + 1);
 
    printCombination(array, size, combinations, resi, result, arri + 1);
}
 
int generateCombinations(int array[], int size, int combinations) {
    int *result = (int*)malloc(size * sizeof(int));
      
    if (result == NULL) {
        return -1;
    }
    
    printCombination(array, size, combinations, 0, result, 0);
     
    free(result);
     
    return 1;
}
 
int main() {
    srand(time(NULL));
    int array[SIZE];
    int N = SIZE;
    int combinations = 3;
    int size = sizeof(array) / sizeof(array[0]);
     
    GenerateNRandomNumbers(N, array, 1, 30);

    printf("array: ");
    for (int i = 0; i < N; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
     
    generateCombinations(array, size, combinations);
     
    return 0;
}
 
 
/*
run:
 
array: 16 28 1 23 10 2 5 
16 28 1 
16 28 23 
16 28 10 
16 28 2 
16 28 5 
16 1 23 
16 1 10 
16 1 2 
16 1 5 
16 23 10 
16 23 2 
16 23 5 
16 10 2 
16 10 5 
16 2 5 
28 1 23 
28 1 10 
28 1 2 
28 1 5 
28 23 10 
28 23 2 
28 23 5 
28 10 2 
28 10 5 
28 2 5 
1 23 10 
1 23 2 
1 23 5 
1 10 2 
1 10 5 
1 2 5 
23 10 2 
23 10 5 
23 2 5 
10 2 5  
 
*/

 



answered Sep 24, 2024 by avibootz
edited Sep 24, 2024 by avibootz

Related questions

1 answer 131 views
1 answer 111 views
1 answer 131 views
1 answer 135 views
1 answer 137 views
2 answers 136 views
...