Given the input string: 923857614
This input can be represented in a matrix as follows:
9 2 3
8 5 7
6 1 4
If we have a moving sequence like this: 423692, it means starting at point 4, moving to 2, then to 3, followed by 6, then 9, and finally reaching 2.
The task is to calculate the length of the path. Initially, the length starts at 0. If the next step is adjacent to the current position, add 1; otherwise, add 2.
Here's an attempt at solving 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++) {
// logic to calculate distance goes 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