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