Use the following code for creating four digit unique number.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int i, n=4, p, q, r,s;
p = rand() % 10; /* First digit can be any within the set */
q = rand() % 9; /* Second digit can be any except one (p) */
/* If p == q, it's safe to add 1 to q, because q's initial value is 0-8 */
if( q == p )
q++;
r = rand() % 8; /* Third digit can be any except two (a or q) */
if( ( r == p ) || ( r == q ) )
{
r++;
if( ( r == p ) || ( r == q ) )
r++;
}
/* More of the same for s. Check against p, q, and r for uniqueness */
s = rand() % 7; /* Fourth digit can be any except three (p, q, or r) */
if( ( s == p ) || ( s == q ) || ( s == r ) )
{
s++;
if( ( s == p ) || ( s == q ) || ( s == r ) )
{
s++;
if( ( s == p ) || ( s == q ) || ( s == r ) )
s++;
}
}
Bookmarks