Generate randomly in XXXX-0000 format

1

How to generate a string randomly in XXXX-0000 format where X can be a letter or number? What I've achieved so far was this:

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 tie it in to the format I want.

    
asked by anonymous 19.04.2018 / 00:42

3 answers

4
  

According to the question, what you want is that the first 4 characters    alphanumeric and the last 4 numeric only :

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

You can use the numero variable to randomly cycle the concatenation between letter or number , checking that numero is even: if > pair , concatenates a letter; if it is odd , concatenates a number .

Use a for loop to generate the 8 characters (

19.04.2018 / 00:57
4

You do not need to use repeat structures to generate alphanumeric values. Just use a base in the toString function, 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}' )
  

The Base36 is a numerical system made up of arabic numerals from 0 to 9, and a hexadecimal number. of letters of the Latin alphabet from A to Z, ex: 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, G, H, (For example, if you want to change the color of the page, you can change the color of the letter).

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;
}
    
19.04.2018 / 07:58
1

A functional approach would look 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}')
    
19.04.2018 / 05:01