4

I have this function to create a random 4 digit number:

    generateCode = function(){
      var fullNumber = [];
     var digit1 = Math.floor(Math.random() * 9) + 1;
     var digit2 = Math.floor(Math.random() * 9) + 1;
     var digit3 = Math.floor(Math.random() * 9) + 1;
     var digit4 = Math.floor(Math.random() * 9) + 1;
     fullNumber.push(digit1, digit2, digit3, digit4);
     this.theCode(fullNumber.join("")) ;
    }

But I need to create a 4 digit random number with no repeating digits.

So "1234" or "9673". But not "1145" or "5668"

Is there an efficient way to do this?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
illscode
  • 41
  • 1
  • 3
  • 4
    an easy way: put all digits on an array, randomize the order, and pick first 4 digits out of the array : http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – juvian Aug 19 '15 at 20:23
  • @juvian related: [How to randomize (shuffle) a JavaScript array?](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – GuiDocs Aug 19 '15 at 20:25
  • May be helpful: http://underscorejs.org/#shuffle – Tomasz Lenarcik Aug 19 '15 at 20:26

5 Answers5

5

You can use this handy shuffle function to shuffle an array containing the numbers, and pick the first 4.

function random4Digit(){
  return shuffle( "0123456789".split('') ).join('').substring(0,4);
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

alert( random4Digit() );

Edit: If you actually want a Number not starting with 0:

function random4DigitNumberNotStartingWithZero(){
    // I did not include the zero, for the first digit
    var digits = "123456789".split(''),
        first = shuffle(digits).pop();
    // Add "0" to the array
    digits.push('0');
    return parseInt( first + shuffle(digits).join('').substring(0,3), 10);
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

alert( random4DigitNumberNotStartingWithZero() );
Community
  • 1
  • 1
blex
  • 24,941
  • 5
  • 39
  • 72
2

Create an array of numbers, randomize it, then slice out the first 4 and join them together.

var numbers = [0,1,2,3,4,5,6,7,8,9];

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

shuffleArray(numbers).slice(0,4).join('');
Dtipson
  • 1,564
  • 16
  • 21
0

It really depends on how you'd like to approach the problem. One solution is to store the digits you've used already in an array, then search the array when you generate a number. If the generated number is contained in the array, then you try generating another number. Doing a few different steps like this is also easier to follow if you have a few different functions. See my included example below:

var checkRandomUsed = function(array, number){
    return array.indexOf(number) > -1;
}
var getCheckedRandom = function(array){
    var random = getRandomNum();
    while (checkRandomUsed(array, random)){
        random = getRandomNum();
    }
    return random;
}
var getRandomNum = function(){
    return Math.floor(Math.random() * 9) + 1;
}
var generateCode = function(){
    var usedNumbers = [];
    for (var i = 0; i < 4; i++){
        usedNumbers.push(getCheckedRandom(usedNumbers));
    }
    return usedNumbers.join("");        
}
Miles Grimes
  • 432
  • 2
  • 16
0

As an update, try this...

const value = (new Array(4))
  .map(() => (Math.floor(Math.random() * 9) + 1).toString()).reduce((p, c) => p + c);
bloo
  • 1,416
  • 2
  • 13
  • 19
0

This will do it if you're ok with potentially having 0 as the first digit:

var getNum = () => randoSequence(0, 9).slice(-4).join("");

console.log(getNum());
<script src="https://randojs.com/1.0.0.js"></script>

This will do it without 0 as the first digit:

function getNum(){
  var sequenece = randoSequence(0, 9).slice(-4);
  return (sequenece[6] ? sequenece.slice(-4) : sequenece.slice(0, 4)).join("");
}

console.log(getNum());
<script src="https://randojs.com/1.0.0.js"></script>

Both of these codes use rando.js to simplify the randomness and make it more readable, so don't forget to add the script tag to the head of your HTML document if you want to use either of them.

Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15