How to get multiple random elements from an array without duplicates in C

1 Answer

0 votes
// without duplicates
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

bool rand_in_array(int arr[], int size, int j, int n) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == n) return true;
    }
    arr[j] = n;

    return false;
}

int main(void) {
    int arr[] = { 1, 12, 7, 26, 15, 21, 98, 6, 3, 18, 30, 80 };

    int size = sizeof(arr) / sizeof(arr[0]);

    srand(time(NULL));

    int random_elements = 5;
    int tmp_arr[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
    for (int i = 0, j = 0; i < random_elements; i++) {
        while (rand_in_array(tmp_arr, size, j, (rand() % size))); // random from 0 to size
        j++;
    }
    for (int i = 0; i < random_elements; i++) {
        printf("%d ", arr[tmp_arr[i]]);
    }

    return 0;
}



/*
run:

6 30 98 80 12

*/

 



answered Jun 2, 2022 by avibootz

Related questions

...