#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void print(int arr[], int size) {
int i;
for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return;
}
/* http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle */
void shuffle(int arr[], int size_of_arr) {
int i, j, temp;
srand(time(NULL));
for (i = size_of_arr-1; i > 0; --i) {
j = rand() % (i+1);
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int random_c(int* items, int items_weight[], int num_of_items) {
/* Usual variables as array indexes */
int i, j, t;
int counter;
/* Its name tells us everything */
int result;
/* big-array : used for storing the items
* in number of items of its weight */
static int *big_array = NULL;
/* period : equal to the sum of each items weight
* and when random_c(...) is called for number of times
* which is equal to the period, the big_array will be
* shuffled again in order to get a new sequence */
static int period;
/* current : is used to indicate current item in
* big_array as a result of random_c(...) */
static int current;
/* sum of each items weight */
static int total_weight;
/* If a new array of items had been given */
if (items != NULL) {
/* calculate total weight */
total_weight = 0;
for (i = 0; i < num_of_items; ++i) {
total_weight += items_weight[i];
}
/* If random_c(...) was called with an array of items before
* delete the previous big_array and create a new one for
* the new items */
if (big_array != NULL) {
free(big_array);
}
big_array = (int*) malloc(total_weight * sizeof(int));
/* Fıll in the big_array with the given items by using their
* weight as the number of occurence in big_array */
t = 0;
for (j = 0; j < num_of_items; ++j) {
counter = 0;
while (counter < items_weight[j]) {
big_array[t] = items[j];
t++;
counter++;
}
}
/* New array has come, so shuffle the big_array */
shuffle(big_array, total_weight);
period = total_weight;
current = 0;
}
result = big_array[current];
if (++current == period) {
current = 0;
shuffle(big_array, total_weight);
}
return result;
}
int main(int argc, char** argv)
{
int counter;
int arr[] = {1, 2, 3};
int arr_weight[] = {1, 2, 3};
int karr[] = {1, 3, 5, 7};
int karr_weight[] = {1, 3, 5, 7};
printf("----> %d\n", random_c(arr, arr_weight, 3));
counter = 0;
while (counter++ < 17) {
sleep(1); /* I compiled it with gcc */
printf("----> %d\n", random_c(NULL, arr_weight, 3));
}
printf("\n");
printf("----> %d\n", random_c(karr, karr_weight, 4));
counter = 0;
while (counter++ < 31) {
sleep(1);
printf("----> %d\n", random_c(NULL, karr_weight, 4));
}
printf("\n");
return 0;
}