mercredi 22 novembre 2017

Weird pattern when I try to generate a 4-digit integer for which every digit is distinct

When I try to write a small program in C language that is intended to generate a 4-digit integer for which every digit is distinct and nonzero, the returned value is always in pattern like 1abc: the first digit seems to always be 1, and sometimes the returned value will be more than 4-digit like 56127254. Could anyone help me look into this? Thank you very much in advance.

So basically the program includes two functions, int isvalid(int n) and int choose_N(void).

isValid return 1 if the integer consists of exactly 4 decimal digits, and all these digits are nonzero and distinct, and 0 otherwise.

And int choose_N(void) generates an integer that is 4-digit and all the digits are distinct and nonzero.

Here is my code:

#define N_DIGITS 4

....
....//the main function 

int isvalid(int n){
  int i, x; int check[N_DIGITS]={0};
  for(i=1;i<=N_DIGITS;i++){ //check whether all digits are nonzero
    if((check[i-1]=n%10)==0){
      return 0;
    }
    n /= 10;
  }
  for(i=0;i<N_DIGITS-1;i++){ // check whether all digits are distinct
    for(x=i+1;x<N_DIGITS;x++){
      if(check[i]==check[x])
        return 0;
    }
  }
  return 1;
}

int choose_N(void){
  int i; int number=0;
  while(!isvalid(number)){
    for(i=0;i<N_DIGITS;i++){
      srand(time(0));
      number += ((10^i)*(rand()%10));
    }
  }
  return number;
}

For srand(time(0));, I have tried various alternatives like srand(time(0)+i); or put this statement out of while loop, but those attempts seemingly did not work and still the returned value of choose_Nstill showed the werid pattern that I described.

Could anyone help me? I am really new to C.

Thank you veru much^_^!




Aucun commentaire:

Enregistrer un commentaire