具有以下輸入字串: 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
uj5u.com熱心網友回復:
您可以通過使用所有鍵盤值的位置物件并獲取位置的絕對增量來采取不同的方法。
用于添加以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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/417244.html
標籤:
