write a function to calculate the number of milliseconds needed to type a number with one finger in javaScript
am try to solve this question but i don't have any idea how am solve this problem.
If I understand the comments well here's the answer
function calcTime (digits, num ){
const digits_arr = Array.from(digits);
let last_index = 0, new_index, time =0;
for (const n of num) {
new_index =digits_arr.findIndex(x => x===n);
time += Math.abs(new_index - last_index);
last_index = new_index;
}
return time;
}
example: Input: digits = "0123456789", num = "201" Output: 4
Dude, I suppose you didn't have much time to explain what you where trying to solve. But anyway I run into this post because I was trying to understand how to start to solve the problem that I've found and thanks to @AbdelazizAlsabagh I've finally understand the trick with the indexes!. I'm posting the full problem to solve (but I haven't try the solution yet, I'll updated later):
A digit-only keyboard contains all 10 digits from 0 to 9. They all exist in one line. Give a string of 10 digits illustrating how the keys are positioned. To type a digit, you start from index zero to the index of the target digit. It takes |a - b| milliseconds to move from index a to index b.
Write a function to calculate the number of milliseconds needed to type a number with one finger.
Input: digits = '0123456789', num = '210
Output: 4
Input: digits = '8459761203', num = '5439'
Output: 17
Constraints:
def number_gen_idx(digits: str, nums: str) -> str:
"""
>>> number_gen_idx('0123456789', '210')
4
>>> number_gen_idx('8459761203', '5439')
17
"""
digits_idx = defaultdict(int)
for idx, digit in enumerate(digits):
digits_idx[digit] = idx
curr_ptr = 0
result = 0
for digit in nums:
result += abs((digits_idx[digit] - curr_ptr))
curr_ptr = digits_idx[digit]
return result