Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

201
Views
generar 4 números aleatorios únicos en arr?

Si quiero 4 números aleatorios en una matriz [num1, num2, num3, num4], no puedo hacerlo

 function getRandomFloat(min, max) { return Math.random() * (max - min) + min; } const arr = [getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10)]

porque tendré valor duplicado. ¿Hay alguna forma o biblioteca que me permita generar un conjunto único de números aleatorios?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Puede declarar la matriz como vacía y luego continuar agregando valores hasta que tenga 4 números. También puede evitar duplicados usando la condición if.

 function getRandomFloat(min, max) { return Math.random() * (max - min) + min; } var arr=[]; var min=1, max=10; while (arr.length != 4) // executes loop till length of array is 4 { var i = getRandomFloat(min, max); // checking if number already exists in array if (arr.includes(i)) { continue; } arr.push(i); }
about 4 years ago · Juan Pablo Isaza Report

0

Este es un método eficiente para lograrlo. Puede usar Set para obtener los números únicos aleatorios en una matriz

Incluso puede agregar una verificación si unique numbers son posibles o no como

 if (max - min < n) return "Not possible"; 

 function getRandomNumbers(n, min = 0, max = 0) { const set = new Set(); while (set.size !== n) { set.add(Math.random() * (max - min) + min); } return [...set]; } console.log(getRandomNumbers(4, 1, 10));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!