for(x=0;x<4;x++)
{
rbox[x] = rand()%4;
}
Assign each element of array to a different output of rand()
.
Here you are assigning every element of array rbox
to same value (random
) - that explains why you are getting same value.
Shuffle of the array:
As from user's comment it seems that OP wants to create shuffle of the array.
Now to do that either you can initialize the whole array with values 0,1,2,3
and then apply this algorithm
-- To shuffle an array a of n elements (indices 0..n-1):
for i from n−1 downto 1 do
j ← random integer such that 0 ≤ j ≤ i
exchange a[j] and a[i]
This is known as Fisher Yates Shuffle.
Also other ways...
Another way would be to follow this algorithm :-
- Keep track of the range of numbers (this is basically
highestNumInRange - iteration Number
).
- And then keep track of the number of elements you need to generate.
3.1. If the ratio of 2
multiplied with rand()
is less than 1
then put the number of iteration in the array.
3.2. Else increase the iteration.