1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| function solution(numbers, hand) { switch (hand) { case 'left': hand = 'L'; break; default: hand = 'R'; break; } let curleft = '*'; let curright = '#'; let answer = ''; const maptable = { 1: { low: 0, col: 0 }, 2: { low: 0, col: 1 }, 3: { low: 0, col: 2 }, 4: { low: 1, col: 0 }, 5: { low: 1, col: 1 }, 6: { low: 1, col: 2 }, 7: { low: 2, col: 0 }, 8: { low: 2, col: 1 }, 9: { low: 2, col: 2 }, '*': { low: 3, col: 0 }, 0: { low: 3, col: 1 }, '#': { low: 3, col: 2 }, }; let keypad = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [-1, 0, -2], ]; function getCost(num, cur) { let cost = 0; const src = maptable[cur]; const des = maptable[num]; let low = Math.abs(des['low'] - src['low']); let col = Math.abs(des['col'] - src['col']); cost = low + col; return cost; } let x; numbers.forEach((number, idx) => { if (number.toString().match(/[369]/)) { x = 'R'; curright = number; } else if (number.toString().match(/[147]/)) { x = 'L'; curleft = number; } else { const costleft = getCost(number, curleft); const costright = getCost(number, curright); if (costleft == costright) { x = hand; switch (hand) { case 'L': curleft = number; break; default: curright = number; break; } } else if (costleft > costright) { x = 'R'; curright = number; } else { x = 'L'; curleft = number; } } answer += x; }); return answer; } result = solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5], 'right'); result = solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], 'left'); result = solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], 'right');
|