Create unique 6 digit js code

I am trying to generate a 6 digit code using JS.

It must contain 3 digits and 3 characters.

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 result of the code will be 3chars + 3 numbers. I want to just rearrange this value to a random value containing the same 3 characters and 3 numbers

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

+4
source share
4 answers

You can shuffle your current codes using such a function (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 can use it as follows:

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

Here is the updated demo with this code.

+1
source

what you can do is use the call cycle from 6 times and use the random character and random number function one by one, and increase by 1, although this is not a very good option, but it may also offer some flexibility.

0
source

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; } 
0
source

Try the following:

  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 could notice that such code should not be considered truly random, since the basic functions can be predictable depending on the javascipt engine working under it.

0
source

Source: https://habr.com/ru/post/1497335/


All Articles