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

138
Views
¿Por qué una sola asignación a una celda de matriz 2d llena dos celdas a la vez en Javascript?

Tengo este código de esta pregunta de leetcode :

 function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const land: boolean[][] = new Array(n).fill(new Array(n).fill(false)) console.log(land) dig.forEach(spot => { console.log(spot, spot[0], spot[1]) land[spot[0]][spot[1]] = true console.log(land) }) console.log(land) return 0 };

Con esta entrada

 n = 2 artifacts = [[0,0,0,0],[0,1,1,1]] dig = [[0,0],[0,1]]

Con esta salida estándar:

 [ [ false, false ], [ false, false ] ] [ 0, 0 ] 0 0 [ [ true, false ], [ true, false ] ] **but expected => [ [ true, false ], [ false, false ] ] [ 0, 1 ] 0 1 [ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ] [ [ true, true ], [ true, true ] ] **but expected [ [ true, true ], [ false, false ] ]

¿Por qué land[1][0] === true y land[1][1] === true cuando nunca se accede a ellos?

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

0

Este:

 new Array(n).fill(new Array(n).fill(false))

llena la nueva matriz externa con n copias de la misma matriz . El argumento del .fill() externo se calcula una vez, por lo que solo hay una matriz involucrada para la segunda dimensión.

Puede crear varias matrices, una para cada fila:

 const land: boolean[][] = new Array(n); land.fill("dummy value"); land.forEach((_, i, rows) => rows[i] = new Array(n); rows[i].fill(false) );

En el código (editado), la matriz externa primero se llena con un valor ficticio. Eso es necesario porque .forEach() omitirá las entradas no inicializadas en una matriz. Alternativamente, se podría usar un bucle for simple, aunque a menos que n sea enorme, probablemente no importe.

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!