Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique 6 digit code js

Tags:

javascript

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/

like image 968
Man Mann Avatar asked Aug 15 '13 21:08

Man Mann


1 Answers

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.

like image 168
Jason Sperske Avatar answered Oct 07 '22 00:10

Jason Sperske