[프로그래머스] 조이스틱
const solution = (name) => {
let answer = 0
let cursor = 0
const typing = Array(name.length).fill('A')
const isChanged = name
.split('')
.map((data) => (data === 'A' ? true : false))
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
const getAlphabetDistance = (start, end) => {
const startIdx = alphabet.findIndex((char) => char === start)
const endIdx = alphabet.findIndex((char) => char === end)
if (Math.abs(startIdx - endIdx) < Math.ceil(alphabet.length) / 2) {
return Math.abs(startIdx - endIdx)
} else {
return alphabet.length - Math.abs(startIdx - endIdx)
}
}
const getCursorDistance = (cursor, targetIdx) => {
if (Math.abs(cursor - targetIdx) < Math.ceil(typing.length / 2)) {
return Math.abs(cursor - targetIdx)
} else {
return typing.length - Math.abs(cursor - targetIdx)
}
}
while (isChanged.includes(false)) {
const targets = [...isChanged]
for (let [idx, changed] of isChanged.entries()) {
if (changed === true) continue
targets[idx] = getCursorDistance(cursor, idx)
}
const nextTargetIdx = targets.findIndex(
(data) =>
data ===
Math.min(
...targets.map((data) =>
data === false || data === true ? Math.min() : data
)
)
)
const count =
getCursorDistance(cursor, nextTargetIdx) +
getAlphabetDistance(
typing[nextTargetIdx] != undefined
? typing[nextTargetIdx]
: 'A',
name[nextTargetIdx]
)
typing[nextTargetIdx] = name[nextTargetIdx]
answer += count
cursor = nextTargetIdx
isChanged[nextTargetIdx] = true
}
return answer
}