-3

Following are the rules:

Generate random numbers of length N.

Not more than two consecutive digits in a number should be the same.

I written code, but even though 2 same consecutive digits in a number are allowed, it's not working. All unique random numbers are generated.

I keep one temporary variable, which stores the previous number generated, if it matches the present generate number, then discard and generate again.

while (rnum.length<=7)
{
    gennum = randomNumericChar();
    if(rnum.length==0) {
        rnum = rnum.concat(gennum);
        prevnum = gennum;
    } else if(gennum!=prevnum) {            
        rnum = rnum.concat(gennum);
        prevnum = gennum;
    }
}

return rnum;

FOund solution:

Hi, i got the solution.                                                                                        ` var rnum = "" ;
var random;

while(rnum.length<=7)
{
    random= generaterandom();

    if(rnum.length<2)
    {
      rnum = rnum.concat(random);

    }else
    {
      //check whether previous two numbers are same, if not then append generated random number
      if(!(random==rnum.charAt(rnum.length-1) &&  random==rnum.charAt(rnum.length-2)))
      { 
        rnum = rnum.concat(random);        
      } 

    }                   
}`
ashu
  • 579
  • 2
  • 6
  • 17

1 Answers1

1

This might be your solution:

function randomNumericChar(lastNumber) {
    var num = Math.floor((Math.random() * 10) + 1);

    if (lastNumber !== null && num === lastNumber) {
        return randomNumericChar(lastNumber);
    } else {
        return num;
    }
}

function createNumber(n) {
    var randomNumber = '';
    var lastChar     = null;

    while (randomNumber.length < n) {
        var num = randomNumericChar(lastChar);

        if (((randomNumber.length + 1) % 2) === 1) {
            lastChar = num;
        }

        randomNumber += num;
    }

    return randomNumber;
}

var randomNumber = createNumber(10);

Edit: forgot about the fact that there might be 1 consecutive number.

w00tland
  • 69
  • 7