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

143
Views
Calcule la distancia entre elementos en una matriz bidimensional en Javascript

Tener la siguiente cadena de entrada: 923857614

Esto se representa en una matriz como esta:

 9 2 3 8 5 7 6 1 4

Teniendo una secuencia de movimiento como esta: 423692, esto quiere decir que comenzamos en el punto 4, nos movemos al 2, luego al 3, luego al 6, luego al 9 y finalmente al 2.

Se debe calcular la longitud del camino. Al principio parte de 0, si el siguiente paso es contiguo al actual, suma 1, si no es contiguo, suma 2.

Cómo traté de hacerlo:

 function computeRoadLength(keypad, movingSequence) { // build the matrix const arr = [[keypad[0], keypad[1], keypad[2]], [keypad[3], keypad[4], keypad[5]], [keypad[6], keypad[7], keypad[8]]]; let roadLength = 0; for (i = 0; i < movingSequence.length; i++) { // some way to compute the distance here if (arr[i] > arr[i+1]) roadLength = roadLength + 1; if (arr[i] < arr[i+1]) roadLength = roadLength + 2; } return roadLength; } computeRoadLength(923857614, 423692); // 2 + 1 + 2 + 2 + 1 = 8, should return 8
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Podría adoptar un enfoque diferente usando un objeto de posiciones de todos los valores del teclado y tomando el delta absoluto de las posiciones.

Para agregar a movingSequence agregue uno o dos como máximo.

 function computeRoadLength(keypad, movingSequence) { const positions = {}; for (let i = 0; i < keypad.length; i++) { positions[keypad[i]] = [Math.floor(i / 3), i % 3]; } let roadLength = 0, last = positions[movingSequence[0]]; for (let i = 1; i < movingSequence.length; i++) { const item = positions[movingSequence[i]], sum = Math.abs(last[0] - item[0]) + Math.abs(last[1] - item[1]); roadLength += Math.min(sum, 2); last = item; } return roadLength; } console.log(computeRoadLength('923857614', '423692')); // 2 + 1 + 2 + 2 + 1 = 8

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!