FCorreia
FCorreia

Reputation: 91

Unique Four Digit Pin Generator Between 0 and 9

Im trying to build an unique pin generator so that the 4 pin numbers never have 3 or more consecutive numbers. Here is what i got:

function getRandomNumber(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function saveToArray() {
  let arr = [];
  for (let index = 0; index < 4; index++) {
    let result = getRandomNumber(0, 9);
    arr.push(result);
  }
  /* if (consecutive(arr)) {
    console.log('1', arr);
    return arr;
  } else {
    saveToArray;
  } */
  return arr;
}

/* function consecutive(arr) {
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] != arr[i - 1] + 1) {
      return false;
    }
  }
  return true;
} */

console.log(saveToArray());

The consecutive function is making only having pins like [0,1,2,3] or [4,5,6,7] and if i comment it out the pin gets generated but i dont have that function to validate the consecutive numbers by ascending or descending order.

Any tip on what im missing ?

Upvotes: 0

Views: 289

Answers (3)

Marc
Marc

Reputation: 1467

This code returns random pins with non equal and non consecutive numbers. When the same or consecutive digit found, I add 3%10 to the result, I think it's enough.

function randomD() {
  return Math.floor(Math.random() * 10);
}

var fullRand = "", iNewRand, iRand;
for (var i = 0; i < 4; i++) {
  iNewRand = randomD();
  if (i > 0) {
    if (Math.abs(iNewRand - iRand) <= 1) {
      iRand = (iNewRand + 3) % 10;
    }
    else {
      iRand = iNewRand;
    }
  }
  else {
    iRand = iNewRand;
  }
  fullRand += iRand;
}
console.log(fullRand);

Upvotes: 0

IWHKYB
IWHKYB

Reputation: 491

To check if a number is consecutive you could do this:

function isConsecutive(n1, n2) {
  return Math.abs(n1 - n2) === 1;
};

And one way to validate your array, considering cases as 1,2,3,4 and 7,6,5,4 could be like this:

function isValid(array) {
    for (let i = 0; i + 2 < array.length; i++) {
        let n1 = array[i], n2 = array[i+1], n3 = array[i+2];
        if (isConsecutive(n1, n2) && isConsecutive(n2, n3))
          return false;
    }
    return true;
};

Upvotes: 1

varontron
varontron

Reputation: 1157

consecutive integers differ by 1. you can just add the differences between consecutive indices

function nonConsecutive(x) {  
    console.log(x)
    if((x[1]-x[0]) + (x[2]-x[1]) == 2 || (x[3]-x[2]) + (x[2]-x[1]) == 2)
        return false
    return true
}

Upvotes: 0

Related Questions