Man Mann
Man Mann

Reputation: 423

Generating unique 6 digit code js

I am trying to generate 6 digit code using JS.

it must contains 3 digits and 3 chars.

here is my code

var numbers = "0123456789";
var chars = "acdefhiklmnoqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var randomstring2 = '';
for (var x = 0; x < string_length; x++) {
    var letterOrNumber = Math.floor(Math.random() * 2);
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum, rnum + 1);
}
for (var y = 0; y < string_length; y++) {
    var letterOrNumber2 = Math.floor(Math.random() * 2);
    var rnum2 = Math.floor(Math.random() * numbers.length);
    randomstring2 += numbers.substring(rnum2, rnum2 + 1);
}
var code = randomstring + randomstring2;

the code result will be 3chars + 3 numbers .. I want to just rearrange this value to be random value contains the same 3 chars and 3 numbers

http://jsfiddle.net/pgDFQ/101/

Upvotes: 5

Views: 8668

Answers (4)

aperl
aperl

Reputation: 144

Try this:

  var numbers = "0123456789";

  var chars= "acdefhiklmnoqrstuvwxyz";

  var code_length = 6;
  var didget_count = 3;
  var letter_count = 3;

  var code = '';

  for(var i=0; i < code_length; i++) {
     var letterOrNumber = Math.floor(Math.random() * 2);
     if((letterOrNumber == 0 || number_count == 0) && letter_count > 0) {
        letter_count--;
        var rnum = Math.floor(Math.random() * chars.length);
        code += chars[rnum];
     }
     else {
        number_count--;
        var rnum2 = Math.floor(Math.random() * numbers.length);
        code += numbers[rnum2];
     }
  }

I might note that such a code should not be considered truly random as the underlying functions could be predictable depending on the javascipt engine running underneath.

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30446

You could shuffle your current codes with a function like this (from this answer)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    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;
};

You could use it like this:

alert(shuffle("StackOverflow".split('')).join(''));

Here is an updated demo with this code.

Upvotes: 2

Ruslan
Ruslan

Reputation: 3048

Here is the code for you

function(count){
  var chars = 'acdefhiklmnoqrstuvwxyz0123456789'.split('');
  var result = '';
  for(var i=0; i<count; i++){
    var x = Math.floor(Math.random() * chars.length);
    result += chars[x];
  }
  return result;
}

Upvotes: 2

Akash Arora
Akash Arora

Reputation: 71

what you can do is use a dingle loop from 6 times and use random character and random number function one by one while also incrementing by 1, Although not that a good option but this may also offer some flexibility

Upvotes: 1

Related Questions