Problems when allocate an array of 6 random number unique

Viewed 67

So I want to generate an array of random numbers from 1 to 6 (unique) with 60% chance of appearing 0 (non-unique). Here's what I did.

#define SIZE 6
int *t_size(){
    int i, j;
    int *tab; 
    tab = (int*)malloc(sizeof(int) * SIZE);
    int randnum;
    bool chance = rand() <= 0.6;

    for(i = 0; i < SIZE; i++){
        randnum = rand() % (SIZE+ 1);
        printf("%d \n",randnum);
        if(randnum == 0){
            if (chance){
                tab[i] = randnum;
                continue;
            }
        }
        else{
            for(j = 0; j < i; j++){
                    if(randnum == tab[j])
                        break;
            }
            if (i == j){ 
                tab[i] = randnum;
                printf("tab [%d] val %d \n",i, tab[i]);
            }
            else 
                i--;
        }
    }
    return tab;

Here is my output

1 
tab [0] val 1
6
tab [1] val 6
5
tab [2] val 5
3
tab [3] val 3 
2
tab [4] val 2
5
0
1 6 5 3 2 691419256

For some reason, on the 5th element, it stopped working and instead show a bunch of random number(which I think is address ?) So I think it is my allocation with malloc that caused the problem but I don't know how to fix it. Also any suggest/advice with the algorithm would be nice.

P/s: for reference, SIZE is defined by 6

1 Answers

Here is an algorithm:

  • Fill an array with the numbers 1-6, in order;
  • Iterate through the array and at each index, draw a random number to decide whether to keep the number or replace it by 0, with a probability of 60%;
  • Perform a Fisher-Yates shuffle on the array.
#include <stdlib.h>

void shuffle(int *array, unsigned int size)
{
    unsigned int i;
    unsigned int j;
    int tmp;
    for (i = 0; i < size; ++i)
    {
        j = i + (unsigned int) ((double) rand() / RAND_MAX) * (size - i);
        tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
}

int *random_array(unsigned int size, double nonzero_chance)
{
    int *array = malloc(sizeof(int) * size);
    unsigned int i;

    for (i = 0; i < size; ++i)
    {
        if ((double) rand() < nonzero_chance * RAND_MAX)
        {
            array[i] = i+1;
        }
        else
        {
            array[i] = 0;
        }
    }
    shuffle(array);
    return array;
}
Related