计算 Javascript 中二维数组中元素之间的距离

Compute the distance between elements in a bi-dimensional array in Javascript

具有以下输入字符串:923857614

这表示为这样的矩阵:

9 2 3
8 5 7
6 1 4 

移动顺序如下:423692,这意味着我们从点 4 开始,移动到 2,然后移动到 3,然后移动到 6,然后移动到 9,最后移动到 2。

必须计算道路的长度。一开始是从0开始,如果下一步与当前一步相邻则加1,如果不相邻则加2。

我是怎么做到的:

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

您可以采用不同的方法,使用所有键盘值的位置对象,并获取位置的绝对增量。

要添加到 movingSequence 添加一个或最多两个。

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