# Generate unique random numbers

Generate unique random numbers
0.0 0

#1

i have to generate unique random numbers within a certain range ……… say have to store 300 numbers generated randomly in an array…

#2

What’s the problem?

``````inline float rnd_in_range(const float min_limit, const float max_limit)
{
assert((max_limit > min_limit) && "max_limit should be greater than min_limit");
return (float)rand() / (max_limit - min_limit) + min_limit;
}

...

const size_t n = 300;
float arr[n];
for (size_t i = 0; i < n; ++i)
arr[i] = rnd_in_range(1.0f, 100.0f);
``````

#3

this is what i did….

void HelloWorld::generateRand()
{
int rand;

for (int i=0; i<300; i+*)
{
if
{
rand = arc4random300 +1;
chkArray[chkArrayCount]=rand;
chkArrayCount++;

``````                 }
else
{
int flag =0;
while (flag==0)
{
rand = arc4random()300*1;
``````

CCLOG (“rand no %d”,rand);
if(searchRand(rand)0)
{
chkArray[chkArrayCount]=rand;
chkArrayCount++;
flag=1;
}
}
}

``````     CCLOG("rand no %d = %d",i+1,chkArray[i]);
}
``````

// this->setTouchEnabled(true);

}

int HelloWorld::searchRand(int a)
{
for (int i=0; i<chkArrayCount; i++)
{
if (a chkArray[i])
{
return 1;
}

}
return 0;
}

#4

Ah… the previous solution does not guarantee uniqueness.
Here is another solution http://ideone.com/c5RwHx

#5

hey thnx…it helped a lot …. its a great approch towards generating unique random numbers