//이건 하드 코딩 안 하면 방법이 없지 않나...
const KEYPAD = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
["*", 0, "#"],
];
// 이후 수시로 좌표값을 얻어내야하기 때문에 해쉬를 만들어준다.
const initCoordinates = () => {
const hashTable = {};
const lengthOfRow = KEYPAD.length;
const lengthOfCol = KEYPAD[0].length;
for (let i = 0; i < lengthOfRow; i++) {
for (let j = 0; j < lengthOfCol; j++) {
const current = KEYPAD[i][j];
hashTable[current] = [i, j];
}
}
return hashTable;
};
// 거리계산
const calculateDistance = ([fromRow, fromCol], [toRow, toCol]) => {
if (fromRow == toRow && fromCol == toCol) {
return 0;
}
if (fromRow == toRow) {
return 1;
}
if (fromCol == toCol) {
return Math.abs(toRow - fromRow);
}
return Math.abs(toRow - fromRow) + 1;
};
const solution = (numbers, hand) => {
let result = "";
const coordinates = initCoordinates();
let leftCoordinates = coordinates["*"];
let rightCoordinates = coordinates["#"];
const clickedByLeft = (current) => {
result += "L";
leftCoordinates = coordinates[current];
};
const clickedByRight = (current) => {
result += "R";
rightCoordinates = coordinates[current];
};
for (const num of numbers) {
const currentCoordinates = coordinates[num];
switch (num) {
case 1:
case 4:
case 7: {
clickedByLeft(num);
break;
}
case 3:
case 6:
case 9: {
clickedByRight(num);
break;
}
case 2:
case 5:
case 8:
case 0: {
const leftDistance = calculateDistance(
currentCoordinates,
leftCoordinates
);
const rightDistance = calculateDistance(
currentCoordinates,
rightCoordinates
);
if (leftDistance < rightDistance) {
clickedByLeft(num);
} else if (leftDistance > rightDistance) {
clickedByRight(num);
} else {
if (hand == "left") {
clickedByLeft(num);
} else {
clickedByRight(num);
}
}
break;
}
}
}
return result;
};
코드가 개판인 건 둘째 치고, reduce를 쓰고 싶은데 reduce함수에 넘겨 줄 수 있는 인자가 고정되어 있어 어려운 것 같다.
정해진 인자 외에 다른 인자를 전달할 수 없기에 결국 전역 스코프에 변수들을 선언시켜 접근하게 해야했는데 hand같은 인자는 그마저도 어려웠다.
결국 함수형으로 풀지 못하고 명령형으로 풀었다.
이게 레벨 1이라고?