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

97
Views
Detener duplicados en una matriz

El problema ha sido resuelto

Lo que necesito es si declaro n como 4. Necesito 4 coordenadas únicas y las empujo a la matriz, aquí está mi código que puede producir duplicados:

 function entriesToDel(n) { var array = []; for (let i = 0; i < array.length; i++) { var row = Math.round(3*Math.random()); var col = Math.round(3*Math.random()); var output = [row,col]; array.push(output); } return array; }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Lo que puede hacer es simplemente poner una verificación basada en condiciones para las coordenadas.

por ejemplo, puedes hacer algo como,

 function entriesToDel(n) { var array = []; for (var i = 0; i < n; i++) { const repeat = () => { var row = Math.round(3 * Math.random()); var col = Math.round(3 * Math.random()); var coords = [row, col]; let sameEntry = array.find(i => i[0] === row && i[1] === col) if (sameEntry) { repeat(); } else { array.push(coords); } } repeat(); } console.log(array); return array; }

about 4 years ago · Juan Pablo Isaza Report

0

En lugar de crear las coordenadas al azar, mezcla una matriz con todas las coordenadas de 3x3 y elige la primera n de ellas:

 function shuffle(a) { // Generic shuffle function for (let i = a.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let x = a[i]; a[i] = a[j]; a[j] = x; } return a; } function entriesToDel(n) { // Generate all possible coordinates in a 3x3 grid let coord = Array.from({length: 3}, (_, i) => Array.from({length: 3}, (_, j) => [i, j]) ).flat(); // Shuffle and select return shuffle(coord).slice(0, n); } console.log(entriesToDel(4));

about 4 years ago · Juan Pablo Isaza Report

0

Simplemente puede cambiar su ciclo for en un ciclo while, y simplemente terminar cuando array.length sea igual a su parámetro.

Puede usar Arrray.some() para verificar si ya tiene la coordenada.

p.ej.

 function entriesToDel(n) { var array = []; while (array.length < n) { var row = Math.round(3*Math.random()); var col = Math.round(3*Math.random()); var coords = [row,col]; if (!array.some(([r,c]) => r === row && c === col)) array.push(coords); } return array; } console.log(entriesToDel(4));

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!