Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

303
Vistas
¿Crear una nueva matriz a partir de un generador aleatorio ()?

Estoy tratando de crear una nueva matriz con 5 nombres aleatorios tomados de una matriz con 897 nombres. Esto es lo que traté de hacer, pero no estoy seguro de cómo especificar que solo quiero 5 nombres:

 for(let i = 0; i < pokemon.all().length; i++){ pokedex = [i]; }; app.get('/dex', (req, res) => { res.send(pokedex) });
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

 function pickNOf(list, n) { // - create a new shallow array copy. // - does decouple the original reference, thus it // prevents its further mutation by eg `splice`. list = Array.from(list); // - creates and returns an array of the desired length. return Array.from({ length: n }, () => list.splice( // - `splice` does mutate the list by removing a // single item from its randomly chosen index. Math.floor(Math.random() * list.length), 1 )[0]); } const listOfAllPokemonNames = [ "Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise", "Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill", "Pidgey" ]; console.log( "pickNOf(listOfAllPokemonNames, 5) ...", pickNOf(listOfAllPokemonNames, 5) ); console.log( "pickNOf(listOfAllPokemonNames, 9) ...", pickNOf(listOfAllPokemonNames, 9) ); console.log( "pickNOf(listOfAllPokemonNames, 3) ...", pickNOf(listOfAllPokemonNames, 3) );
 .as-console-wrapper { min-height: 100%!important; top: 0; }

El uso dentro del código del OP se ve así ...

 function pickNOf(list, n) { list = Array.from(list); return Array.from({ length: n }, () => list.splice( Math.floor(Math.random() * list.length), 1 )[0]); } app.get('/dex', (req, res) => { res.send(pickNOf(pokemon.all(), 5)) });
about 4 years ago · Juan Pablo Isaza Denunciar

0

Eche un vistazo a esto, use Math.random() para generar un índice aleatorio y obtenerlo de la matriz de pokemons, luego desactive el valor de pokemons para que no tenga doublon en pokedex.

 let pokemons = ['pika1','pika2','pika3','pika4','pika5','pika6','pika7'] let pokedex = []; for (i = 0; i < 5; i++) { id = Math.floor(Math.random() * pokemons.length); pokedex.push(pokemons[id]); pokemons.slice(i,1) } //app.send() here... console.log(pokedex)

EDITAR: Teniendo en cuenta que tiene un pokemon.random() generator(?) En este paquete npm. Simplemente use:

 let pokedex = []; for(let i = 0; i < 5; i++) pokedex.push(pokemon.random()); app.get('/dex', (req, res) => { res.send(pokedex) });

EDIT N°2: Uso de objetos

 let pokedex = []; for (i = 0; i < 5; i++) { let pokemon = { name:pokemon.random(), attack:Math.floor(Math.random() * (100 - 50 + 1) +50), defense:Math.floor(Math.random() * (100 - 50 + 1) +50) }; pokedex.push(pokemon); } function attack(attacker,defenser) { defenser.defense -= attacker.attack return attacker && defenser; } function fakeMatch(attacker,defenser) { attack(attacker,defenser) } console.log(pokedex) fakeMatch(pokedex[0],pokedex[3]) console.log('RESULT Pokedex 0 attacked Pokedex 3') console.log(pokedex)

EDIT N°3: Objeto con función (forma correcta)

 let pokemons = ['pika1', 'pika2', 'pika3', 'pika4', 'pika5', 'pika6', 'pika7'] let pokedex = []; for (i = 0; i < 5; i++) { let id = Math.floor(Math.random() * pokemons.length); let pkm = { name: pokemons[id], life: 100, strenght: Math.floor(Math.random() * (100 - 50 + 1) + 50), defense: Math.floor(Math.random() * (100 - 50 + 1) + 50), attack: function(target) { target.life -= this.strenght; console.log(this.name + ' attack ' + target.name) console.log(target.name + ' loose ' + this.strenght + ' of life') //Test if life > 0 or anything else with % defense etc... if (target.life <= 0) { console.log(target.name + ' is dead') } } }; pokedex.push(pkm); pokemons.slice(id, 1) } pokedex[0].attack(pokedex[1]);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda