mercredi 27 décembre 2017

synchronize.js used with express js

I want to generate a random number between 0-3(included) and that number shouldn't be generated before e.g. the number generated was 1, saved in an array, then 3, saved in an array, then again 3, oh-oh it exists in the array so again generated 0, saved in array, then 2 and finally all are saved in the array in the order of 1,3,0,2. But sometimes luck isn't on my side and the function returns the random number before comparing with the numbers present in the array. This is the code I have tried so far:-

  //using synchronized.js
    function f1(choices){
  sync.fiber(function(){
    var options = {     //rand for a choice
      min: 0,
      max:  3,    //choice can be from 0-3 index
      integer: true
    };
    var randomnumber=rn(options);     //random number for choice placement here
    for(var i=0;i<choices.length;i++){
      if(randomnumber==choices[i]){   //if exists, generate the number again
        console.log("rnd generated is: ",randomnumber);
        randomnumber=rn(options);
        i=0;
      }
    }
    console.log("rnd got is: ", randomnumber);
    choices[choices.length]=randomnumber;
    return randomnumber;
  }, function(err,result){
    console.log("sync index is: ",result);
  });
}

But the above solution isn't working i.e. I am getting repeated indices. I have also tried this solution using deasync :-

function randomChoiceNumber(choices){
  var flag=true;
  var count=0;
  return new Promise(function(resolve,reject){
  var options = {     //rand for a choice
    min: 0,
    max:  3,    //choice can be from 0-3 index
    integer: true
  };
  var randomnumber=rn(options);     //random number for choice placement here
  for(var i=0;i<choices.length;i++){
    if(randomnumber==choices[i]){   //if exists, generate the number again
      flag=false;
      randomnumber=rn(options);
      i=0;
      count=0;
    }else{
      count++;
    } 
  }
  while(count != choices.length && choices.length>0) {
    deasync.sleep(100);
  }
  choices[choices.length]=randomnumber;
  resolve(randomnumber);
  });
}

Both aren't working the deasync one goes to sleep lol generates only 1 to 2 indices. Please help me in achieving what I want, I am stuck on this thing for hours. Thank you.




Aucun commentaire:

Enregistrer un commentaire