Generate randomly in XXXX-0000 format

Asked

Viewed 268 times

1

How to generate a string randomly in the format XXXX-0000 where X can it be a letter or a number? What I have achieved so far is as follows::

var letra = String.fromCharCode(65+Math.floor(Math.random() * 26))
var numero = Math.floor(Math.random() * 9);

Generates a letter, and a random number. However, I do not know how to make a loop of this to stay in the format I want.

  • 1

    The 0000 are fixed or is the place where will generate numbers ?

3 answers

5

You do not need to use repeat structures to generate alphanumeric values. Just use a base in the function toString, for example:

let first = Math.random()       // Gera um valor randômico
                .toString(36)   // Utiliza a Base36
                .substr(-4)     // Captura os 4 últimos números
                .toUpperCase(); // Converte para maiúscula 
                
let last = Math.floor((Math.random() * (9999 - 1000)) + 1000); // Gera um valor entre 999 e 10000

console.log( `${first}-${last}` )

To Base36 is a numerical system consisting of Arabic numerals from 0 to 9 and Latin letters from A to Z, e.g.: 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z (note that letters may be uppercase or lowercase letters).

for (let num = 0; num <= 35; num++) {
  var a = num.toString();   // Decimal
  var b = num.toString(2);  // Binário
  var c = num.toString(8);  // Octal
  var d = num.toString(16); // Hexadecimal
  var e = num.toString(36); // Hexatrigesimal

  var n = a + " | " + b + " | " + c + " | " + d + " | " + e + "<br><br>";

  document.body.innerHTML += n;
}

  • The idea is one of the best, but it would be good to adjust your Random to start from 10000 on the basis of 36, (which is 1679616) to ensure always pick up 4 digits (and do the same in last)

4


According to the question, what is desired is that the first 4 characters are alphanumeric and the last 4 numerical only:

          ┌──────┐   ┌──────┐
          │ XXXX │ - │ 0000 │
          └──────┘   └──────┘
              ↑         ↑
     alfanuméricos     numéricos
(números ou letras)

You can use the variable numero to randomly switch the concatenation between letter or number, checking whether numero is par: if it’s par, concatenates a letter; if it is unique, concatenates a number.

Use a bow tie for to generate the 8 characters (4 alphanumerics + 4 numerics):

for(var x=1, alfanum = num = ""; x<5; x++){
   var letra = String.fromCharCode(65+Math.floor(Math.random() * 26));
   var numero = Math.floor(Math.random() * 9);
   var numero2 = Math.floor(Math.random() * 9);
   alfanum += numero%2 == 0 ? letra : numero; // verifico se 'numero' é par para formar a sequência alfanumérica
   num += numero2; // formo a sequência numérica
}
console.log(alfanum+"-"+num);

1

A functional approach would be like this:

const geraAlpha = () => {
  return String.fromCharCode(65 + Math.floor(Math.random() * 26))
}

const geraNumero = () => {
  return Math.floor(Math.random() * 10)
}

const reduce = Array(4).fill(0).reduce(prev => {
  return {
    alpha: prev.alpha + geraAlpha(), 
    numero: prev.numero+ geraNumero()
  }
}, {alpha: '', numero: ''})

console.log(`${reduce.alpha}-${reduce.numero}`)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.