Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
Compute the distance between elements in a bi-dimensional array in Javascript

Having the following input string: 923857614

This is represented into a matrix like this:

9 2 3
8 5 7
6 1 4 

Having a moving sequence like this: 423692, this means that we start in point 4, we move to 2, then to 3, then to 6, then to 9 and finally to 2.

It must be computed the length of the road. At beginning it starts from 0, if the next step is adjacent to the current one, add 1, if it isn't adjacent, add 2.

How I tried to do it:

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 Respostas
Responde à pergunta

0

You could take a different approach by using an object of positions of all keypad values and take the absolute delta of the positions.

For adding to movingSequence add one or max two.

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda