Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

김준우 코팅테스트 (계산기) #14

Open
wants to merge 27 commits into
base: main
Choose a base branch
from

Conversation

cyoure
Copy link
Contributor

@cyoure cyoure commented Dec 6, 2023

두 개 뽑아서 더하기 문제 빼고 완료했습니다.

Copy link
Collaborator

@hobiJeong hobiJeong Dec 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어디서부터 손봐서 피드백을 올릴 지 모르겠어서 코드 컨벤션만 수정해드리고 그냥 제가 예전에 풀었던 코드를 올리겠습니다.

function solution(array, commands) {
    let arrSum = [];
    const answer = [];
      
      for (let i = 0; i < commands.length; i++) {
        arrSum = array.slice(commands[i][0] - 1 , commands[i][1]);
        arrSum.sort((a , b) => a - b);
        answer.push(arrSum[commands[i][2] - 1] );
      }
    return answer;
  }

풀이에 문제가 있는건 아닌데 일단 준우님 코드에서 i, j, k는 선언을 할 필요가 없어 보이고 이를 수정해서 피드백을 올리면 그냥 다른 코드가 될 것 같아서 이렇게 올립니다.

let i;
let j;
let k;
let ArrNum = commands.length;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let ArrNum = commands.length;
let arrNum = commands.length;

let ArrNum = commands.length;
let answer = 0;
const arr = new Array();
for (let a = 0; a < ArrNum; a++) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for (let a = 0; a < ArrNum; a++) {
for (let i = 0; i < arrNum; i++) {

for문에선 보통 i를 선언해서 사용합니다.

j = commands[a][1];
k = commands[a][2];
let array1 = array.slice(i - 1, j);
array1 = array1.sort((a, b) => a - b);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
array1 = array1.sort((a, b) => a - b);
array1.sort((a, b) => a - b);

굳이 이렇게 따로 할당안해도 sort를 돌리면 정렬된 배열로 변합니다.

Comment on lines 7 to 8
answer = false;
return answer;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
answer = false;
return answer;
return answer = false;

이렇게 한줄로도 가능할 것 같아요

@@ -0,0 +1,9 @@
function solution(n) {
const strN = String(n);
let splitN = strN.split("");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let splitN = strN.split("");
const splitN = strN.split("");

splitN은 변경되지 않는 상수이기 때문에 const로 선언해주시면 되겠습니다. Number(splitN[i])를 한다고 해서 splitN의 값이 변하는게 아니기 때문입니다.

Comment on lines 6 to 8
if (isNaN(splitS[i]) === true) {
answer = false;
return answer;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (isNaN(splitS[i]) === true) {
answer = false;
return answer;
if (isNaN(splitS[i]) {
return false

isNaN( value ) 메소드는 value값이 NaN이면 true를, 아니면 false를 반환하는 메소드기 때문에 굳이
isNaN이 true인지 false인지 조건을 주지 않아도 돼요

@@ -0,0 +1,9 @@
function solution(n) {
const strN = String(n);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

비슷한 개념으로 .toString이란 메소드도 있습니다! 한번 참고해보셔요

Comment on lines 2 to 4
let i;
let j;
let k;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let i;
let j;
let k;
let i, j, k;

이런방식으로 선언이 가능합니다.

@@ -0,0 +1,19 @@
function solution(numbers) {
let Arr = [];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let Arr = [];
const arr = [];

배열, 객체는 상수로 선언해도 안에있는 값 변경이 가능합니다.

우리 집 안에 가구들이 많이 있는데, 그 가구들을 바꾼다 해서 집이 안바뀌는 거라고 생각하시면 편합니다.
그리고 변수 선언시에는 Arr보다는 arr로하는게 적절합니다. 대문자로 선언하게 되면, 변수가 아닌 다른 값으로 인식될 여지가 있습니다.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

배열, 객체는 상수로 선언해도 안에있는 값 변경이 가능합니다.

우리 집 안에 가구들이 많이 있는데, 그 가구들을 바꾼다 해서 집이 안바뀌는 거라고 생각하시면 편합니다. 그리고 변수 선언시에는 Arr보다는 arr로하는게 적절합니다. 대문자로 선언하게 되면, 변수가 아닌 다른 값으로 인식될 여지가 있습니다.

맞는 말씀이신데 여기선 arr에 직접적으로 값을 할당해주는 코드가 있어서 const를 사용하면 오류가 납니다.

Comment on lines 15 to 17
Arr = Arr.sort(function (a, b) {
return a - b;
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Arr = Arr.sort(function (a, b) {
return a - b;
});
arr = arr.sort((a, b) => {
return a - b;
});

익명함수는 이렇게 arrow function으로 사용이 가능합니다. 나중에는 이 방법을 더 많이 쓰니깐 알아두면 좋습니다.

Copy link
Collaborator

@hobiJeong hobiJeong Dec 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

익명함수는 이렇게 arrow function으로 사용이 가능합니다. 나중에는 이 방법을 더 많이 쓰니깐 알아두면 좋습니다.

스크린샷 2023-12-08 오후 9 04 07

이 경우엔 중괄호랑 return도 생략하는 패턴을 많이 쓰긴 합니다

Comment on lines 10 to 11
answer = participant[i];
break;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어짜피 같지 않으면 바로 break하니깐 return으로 바로 빠져나와도 괜찮을 것 같네요

@cyoure cyoure changed the title 3일차 코팅테스트 김준우 코팅테스트 (로또까지 완료) Dec 11, 2023
}
}
for(let i = 0; i<=1; i++){
if(ZeroCount + count == i)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

타입과, 값이 같다면 ==보다는 ===가 적절할 것 같습니다.

@cyoure cyoure changed the title 김준우 코팅테스트 (로또까지 완료) 김준우 코팅테스트 (가장 적은 수 제거하기까지 완료) Dec 12, 2023
@cyoure cyoure changed the title 김준우 코팅테스트 (가장 적은 수 제거하기까지 완료) 김준우 코팅테스트 (음양 더하기까지 완료) Dec 12, 2023
@cyoure cyoure changed the title 김준우 코팅테스트 (음양 더하기까지 완료) 김준우 코팅테스트 (이상한 문자 만들기) Dec 14, 2023
@cyoure cyoure changed the title 김준우 코팅테스트 (이상한 문자 만들기) 김준우 코팅테스트 (예산) Dec 15, 2023
Comment on lines 19 to 25
for (let i = 0; i < total.length; i++) {
if (total[i] >= 1) {
answer++;
}
}
return answer;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for (let i = 0; i < total.length; i++) {
if (total[i] >= 1) {
answer++;
}
}
return answer;
}
return allStudent.filter(c => c > 0).length;

filter 메소드를 이용해서 1 이상인 배열의 요소가 몇인지 바로 리턴해 줄 수 있어요

@cyoure cyoure requested a review from CBWDG December 26, 2023 13:05
@cyoure cyoure changed the title 김준우 코팅테스트 (신규 아이디 추천) 김준우 코팅테스트 (크레인 인형 뽑기) Dec 26, 2023
for (let i = 0; i < pick.length; i++) {
if (pick[i] === pick[i + 1]) {
answer += 2;
pick.splice(i, 2);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Array.prototype.pop() 이란 메소드도 있어요 한번 찾아보시길!!

Comment on lines 15 to 23
for (let i = 0; i < moves.length; i++) {
for (let j = 0; j < board.length; j++) {
if (board[j][moves[i] - 1] !== 0) {
pick.push(board[j][moves[i] - 1]);
board[j].splice(moves[i] - 1, 1, 0);
break;
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정말 마음에 드네요

  1. 2중 for문 사용해서 반복문과 조건문을 통해서 인형이 있는지에 대한 여부를 판단하고,
  2. 있으면 push 메서드를 이용해 pick(뽑은 인형을 담을 1차원 배열)에 넣어주는 것과
  3. 그 다음에 2차원 배열에서 뽑은 인형 제거해준다.
  4. 마지막으로 루프를 종료시키는 break까지
  5. 찢었습니다.

@cyoure cyoure requested a review from CBWDG December 27, 2023 05:10
@cyoure cyoure changed the title 김준우 코팅테스트 (크레인 인형 뽑기) 김준우 코팅테스트 (비밀지도) Dec 27, 2023
@@ -0,0 +1,52 @@
// 한 뱐의 길이 n
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// 한 뱐의 길이 n
// 한 변의 길이 n

ㅋㅋㅋㅋㅋㅋㅋ

Comment on lines 2 to 52
// 지도 1 === arr1
// 지도 2 === arr2
// 2진수 값을 배열로
// # === 1, # === 0 으로 2진수 표현

function solution(n, arr1, arr2) {
let answer = [];
let newArr1 = [];
let newArr2 = [];
let total = [];
let result = [];
for (let i = 0; i < n; i++) {
newArr1[i] = arr1[i].toString(2);
newArr2[i] = arr2[i].toString(2);
}
for (let i = 0; i < n; i++) {
if (newArr1[i].length < n) {
newArr1[i] = String(newArr1[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
if (newArr2[i].length < n) {
newArr2[i] = String(newArr2[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
total[i] = Number(newArr1[i]) + Number(newArr2[i]);
}
for (let i = 0; i < n; i++) {
if (String(total[i]).length < n) {
total[i] = String(total[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
answer.push(String(total[i]).split(""));
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (answer[i][j] === "1" || answer[i][j] === "2") {
answer[i].splice(j, 1, "#");
} else if (answer[i][j] === "0") {
answer[i].splice(j, 1, " ");
}
}
}
for (let i = 0; i < n; i++) {
result.push(answer[i].join(""));
}
return result;
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// 지도 1 === arr1
// 지도 2 === arr2
// 2진수 값을 배열로
// # === 1, # === 0 으로 2진수 표현
function solution(n, arr1, arr2) {
let answer = [];
let newArr1 = [];
let newArr2 = [];
let total = [];
let result = [];
for (let i = 0; i < n; i++) {
newArr1[i] = arr1[i].toString(2);
newArr2[i] = arr2[i].toString(2);
}
for (let i = 0; i < n; i++) {
if (newArr1[i].length < n) {
newArr1[i] = String(newArr1[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
if (newArr2[i].length < n) {
newArr2[i] = String(newArr2[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
total[i] = Number(newArr1[i]) + Number(newArr2[i]);
}
for (let i = 0; i < n; i++) {
if (String(total[i]).length < n) {
total[i] = String(total[i]).padStart(n, "0");
}
}
for (let i = 0; i < n; i++) {
answer.push(String(total[i]).split(""));
}
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (answer[i][j] === "1" || answer[i][j] === "2") {
answer[i].splice(j, 1, "#");
} else if (answer[i][j] === "0") {
answer[i].splice(j, 1, " ");
}
}
}
for (let i = 0; i < n; i++) {
result.push(answer[i].join(""));
}
return result;
}
function solution(n, arr1, arr2) {
const result = [];
for (let i = 0; i < n; i++) {
const binaryArr1 = arr1[i].toString(2).padStart(n, '0');
const binaryArr2 = arr2[i].toString(2).padStart(n, '0');
const combinedBinary = (parseInt(binaryArr1, 2) | parseInt(binaryArr2, 2))
.toString(2)
.padStart(n, '0');
const rowResult = combinedBinary.replace(/0/g, ' ').replace(/1/g, '#');
result.push(rowResult);
}
return result;
}

음...뭔가 직접 짠 코드에서 더 설명을 해주고 싶은데.
비밀지도의 문제설명에서 하나도 벗어나지 않고 정말 알고리즘을 잘 짠 것 같아.
나도 그렇게 생각하고, 알고리즘이 틀린 부분이 없기 때문에 패스했을테고
정말 잘했습니다.
근데 이 문제를 쭉 읽어보면, for문이 이렇게까지 필요했나 싶어
문제를 읽어보면서 너의 흐름대로 코드를 쭉 작성하는 것도 정말 좋은 방법이고 실제로 그게 정답에 해당된다면
난 더이상 피드백해줄 부분이 컨벤션이나 조금 줄여야 할 부분에 대한 것 밖에 없겠죠??
하지만 내 역할은 코드를 간결하게 해주고, 너가 푼 문제에 해당하는 좀 더 좋은 해답을 던져주는거라고 생각하기 때문에 위와 같은 해답을 던져 준거야. 혹시나 이 해답에 대해서 궁금한게 있으면 언제든지 물어봐도 괜찮아.

@cyoure cyoure changed the title 김준우 코팅테스트 (비밀지도) 김준우 코팅테스트 (다트게임) Dec 28, 2023
Comment on lines 12 to 69
function solution(dartResult) {
let answer = 0;
let total = [];
console.log(total);
for (let i = 0; i < dartResult.length; i++) {
if (dartResult[i] === "S") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 1);
} else {
total.push(dartResult[i - 1] ** 1);
}
}
if (dartResult[i] === "D") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 2);
} else {
total.push(dartResult[i - 1] ** 2);
}
}
if (dartResult[i] === "T") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 3);
} else {
total.push(dartResult[i - 1] ** 3);
}
}
if (i < 3) {
if (dartResult[i] === "*") {
total[0] = total[0] * 2;
}
} else if (i >= 3 && i < 6) {
if (dartResult[i] === "*") {
total[0] = total[0] * 2;
total[1] = total[1] * 2;
}
} else {
if (dartResult[i] === "*") {
total[1] = total[1] * 2;
total[2] = total[2] * 2;
}
}
if (i < 3) {
if (dartResult[i] === "#") {
total[0] = total[0] * -1;
}
} else if (i >= 3 && i < 6) {
if (dartResult[i] === "#") {
total[1] = total[1] * -1;
}
} else {
if (dartResult[i] === "#") {
total[2] = total[2] * -1;
}
}
}
answer = total[0] + total[1] + total[2];
return answer;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
function solution(dartResult) {
let answer = 0;
let total = [];
console.log(total);
for (let i = 0; i < dartResult.length; i++) {
if (dartResult[i] === "S") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 1);
} else {
total.push(dartResult[i - 1] ** 1);
}
}
if (dartResult[i] === "D") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 2);
} else {
total.push(dartResult[i - 1] ** 2);
}
}
if (dartResult[i] === "T") {
if (dartResult[i - 2] === "1" && dartResult[i - 1] === "0") {
total.push(10 ** 3);
} else {
total.push(dartResult[i - 1] ** 3);
}
}
if (i < 3) {
if (dartResult[i] === "*") {
total[0] = total[0] * 2;
}
} else if (i >= 3 && i < 6) {
if (dartResult[i] === "*") {
total[0] = total[0] * 2;
total[1] = total[1] * 2;
}
} else {
if (dartResult[i] === "*") {
total[1] = total[1] * 2;
total[2] = total[2] * 2;
}
}
if (i < 3) {
if (dartResult[i] === "#") {
total[0] = total[0] * -1;
}
} else if (i >= 3 && i < 6) {
if (dartResult[i] === "#") {
total[1] = total[1] * -1;
}
} else {
if (dartResult[i] === "#") {
total[2] = total[2] * -1;
}
}
}
answer = total[0] + total[1] + total[2];
return answer;
}
function solution(dartResult) {
let total = [];
let tempNum = '';
let dart = dartResult.match(/(\d{1,2}[SDT][*#]?)/g);
for(let i = 0; i < dart.length; i++) {
let num = dart[i].match(/\d{1,2}/g)[0];
let bonus = dart[i].match(/[SDT]/g)[0];
let option = dart[i].match(/[*#]/g);
switch(bonus) {
case 'S':
tempNum = Math.pow(num, 1);
break;
case 'D':
tempNum = Math.pow(num, 2);
break;
case 'T':
tempNum = Math.pow(num, 3);
break;
}
if(option != null) {
if(option[0] === '*') {
if(i !== 0) total[i-1] *= 2;
tempNum *= 2;
}
if(option[0] === '#') {
tempNum *= -1;
}
}
total.push(tempNum);
}
return total.reduce((a, b) => a + b, 0);
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이게 너보다 좋은 정답이라고는 할 수 없지만, 코드의 길이를 줄이고 불필요한 반복을 제거하기 위해서 너와는 아예 정반대로 정규표현식과 switch-case문을 사용해봤어.

  1. total - 빈 배열-> 점수 저장, tempNum - 빈 문자열 -> 현재까지 계산된 숫자 임시 저장
  2. dartReesult 문자열에서 숫자, 보너스, 옵션 추출해서 dart에 저장 -> 정규식
  3. 반복문을 통해서 배열의 각 요소에 대해 숫자, 보너스, 옵션 추출 후 보너스에 따라 숫자 계산 -> tempNum에 저장
  4. 옵션이 존재하는 경우, 옵션에 따라 계산된 숫자 변경
  5. tempNum을 total 배열에 push(추가)
  6. total 배열의 모든 요소를 더한 결과를 반환(reduce)

Comment on lines 8 to 47
function solution(N, stages) {
let count = [];
let total = 0;
let failRate = [];
let big = 0;
let answer = [];
for (let i = 1; i < N + 1; i++) {
for (let j = 0; j < stages.length; j++) {
if (stages[j] === i) {
total++;
}
}
count.push(total);
total = 0;
}
for (let i = 0; i < count.length; i++) {
failRate.push(count[i] / stages.length);
stages.length -= count[i];
if (stages.length === 0 && i < count.length) {
for (let j = i + 1; j < count.length; j++) {
failRate.push(0);
}
break;
}
}
for (let j = 0; j < failRate.length; j++) {
for (let i = 0; i < failRate.length; i++) {
big = Math.max(...failRate);
if (big === -1) {
break;
}
if (failRate[i] === big) {
answer.push(i + 1);
failRate.splice(i, 1, -1);
break;
}
}
}
return answer;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
function solution(N, stages) {
let count = [];
let total = 0;
let failRate = [];
let big = 0;
let answer = [];
for (let i = 1; i < N + 1; i++) {
for (let j = 0; j < stages.length; j++) {
if (stages[j] === i) {
total++;
}
}
count.push(total);
total = 0;
}
for (let i = 0; i < count.length; i++) {
failRate.push(count[i] / stages.length);
stages.length -= count[i];
if (stages.length === 0 && i < count.length) {
for (let j = i + 1; j < count.length; j++) {
failRate.push(0);
}
break;
}
}
for (let j = 0; j < failRate.length; j++) {
for (let i = 0; i < failRate.length; i++) {
big = Math.max(...failRate);
if (big === -1) {
break;
}
if (failRate[i] === big) {
answer.push(i + 1);
failRate.splice(i, 1, -1);
break;
}
}
}
return answer;
}
function solution(N, stages) {
const count = Array(N + 2).fill(0); // 각 스테이지별 도전자 수를 저장할 배열
const failRate = []; // 각 스테이지의 실패율을 저장할 배열
const answer = []; // 실패율이 높은 순서대로 스테이지 번호를 저장할 배열
let total = stages.length; // 도전자 수
// 각 스테이지별 도전자 수 계산
for (let stage of stages) {
count[stage]++;
}
// 각 스테이지의 실패율 계산
for (let i = 1; i <= N; i++) {
failRate.push({ stage: i, rate: count[i] / total });
total -= count[i];
}
// 실패율이 높은 순서대로 스테이지 번호 정렬
failRate.sort((a, b) => b.rate - a.rate);
for (let stage of failRate) {
answer.push(stage.stage);
}
return answer;
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

실패율도 다트와 비슷한 이유로 줄여봤는데, 보고 이해안되는 부분 내일 알려줘!!
그리고 실패율은 솔직히 잘 풀었어 내가 준 코드는 참고만 해도 괜찮을 것 같아
그래도 mdn에서 'for...of' 는 꼭 검색해보시길

Comment on lines 1 to 23
function solution(record) {
let key = [];
let answer = [];
let idNick = {};
for (let i = 0; i < record.length; i++) {
answer.push(record[i].split(" "));
}
answer.forEach((element) => {
if (element[2] === undefined){
}
else{
idNick[element[1]] = element[2];
}
});
for (let i = 0; i < record.length; i++) {
if (record[i].includes("Enter")) {
key.push(idNick[answer[i][1]] +"님이 들어왔습니다.");
}
else if (record[i].includes("Leave")) {
key.push(idNick[answer[i][1]] +"님이 나갔습니다.");
}
} return key;
}
Copy link
Collaborator

@CBWDG CBWDG Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function solution(record) {
  let answer = [];
  let idNick = {};

  record.forEach((element) => {
    const [action, userId, nickname] = element.split(" ");
    if (action === "Enter" || action === "Change") {
      idNick[userId] = nickname;
    }
  });

  record.forEach((element) => {
    const [action, userId] = element.split(" ");
    if (action === "Enter") {
      answer.push(`${idNick[userId]}님이 들어왔습니다.`);
    } else if (action === "Leave") {
      answer.push(`${idNick[userId]}님이 나갔습니다.`);
    }
  });

  return answer;
}

결과값을 answer 하나만 두고, 반복문 대신 배열의 각 요소에 대한 값을 한 번씩 리턴하는 forEach만 두 번 쓰는 코드로 바꿔봤습니다.
action = Enter, Change, Leave
userId = uid3323(예시)
nickname = Mina (예시)
이해안되는 부분있으면 질문주십쇼!!
근데 이 문제는 너무 잘풀어서 그냥 참고만 하십셔

Comment on lines 1 to 239
} else {
Ldistance = 3;
}
if (
Rlocation[Rlocation.length - 1] === 0 ||
Rlocation[Rlocation.length - 1] === 5 ||
Rlocation[Rlocation.length - 1] === 9
) {
Rdistance = 1;
} else if (
Rlocation[Rlocation.length - 1] === 2 ||
Rlocation[Rlocation.length - 1] === 6 ||
Rlocation.length === 0
) {
Rdistance = 2;
} else {
Rdistance = 3;
}
if (Ldistance > Rdistance) {
answer.push("R");
Rlocation.push(numbers[i]);
} else if (Ldistance < Rdistance) {
answer.push("L");
Llocation.push(numbers[i]);
} else {
if (hand === "right") {
answer.push("R");
Rlocation.push(numbers[i]);
}
if (hand === "left") {
answer.push("L");
Llocation.push(numbers[i]);
}
}
}
if (numbers[i] === 0) {
if (Llocation[Llocation.length - 1] === 8 || Llocation.length === 0) {
Ldistance = 1;
} else if (
Llocation[Llocation.length - 1] === 5 ||
Llocation[Llocation.length - 1] === 7
) {
Ldistance = 2;
} else if (
Llocation[Llocation.length - 1] === 2 ||
Llocation[Llocation.length - 1] === 4
) {
Ldistance = 3;
} else {
Ldistance = 4;
}
if (Rlocation[Rlocation.length - 1] === 8 || Rlocation.length === 0) {
Rdistance = 1;
} else if (
Rlocation[Rlocation.length - 1] === 5 ||
Rlocation[Rlocation.length - 1] === 9
) {
Rdistance = 2;
} else if (
Rlocation[Rlocation.length - 1] === 2 ||
Rlocation[Rlocation.length - 1] === 6
) {
Rdistance = 3;
} else {
Rdistance = 4;
}
if (Ldistance > Rdistance) {
answer.push("R");
Rlocation.push(numbers[i]);
} else if (Ldistance < Rdistance) {
answer.push("L");
Llocation.push(numbers[i]);
} else {
if (hand === "right") {
answer.push("R");
Rlocation.push(numbers[i]);
}
if (hand === "left") {
answer.push("L");
Llocation.push(numbers[i]);
}
}
}
}
let key = answer.join("");
return key;
}
// 1,4,7인 경우는 무조건 L
// 3,6,9인 경우는 무조건 R
// 2,5,8,0인 경우는 거리를 생각하며 풀어야 함
// 같은 거리인 경우 자기 손잡이에 맞게 들어가야 함
// 거리를 알아야 한다 ? 이것이 가장 중요한 부분
// 거리가 같은면 hand를 이용

// 왼손과 오른손의 엄지손가락만 이용해서 숫자만 입력
// 엄지손가락은 상하좌우 4가지 방향으로만 이동할 수 있으며 키패드 이동 한 칸은 거리로 1에 해당합니다.
// 1 / 4 / 7을 입력할 때는 왼손 엄지손가락을 사용합니다
// 3 / 6 / 9을 입력할 때는 오른손 엄손이용
// 가운데 열의 4개의 숫자 2 5 8 0 을 입력할 때는 더 가까운 손가락 이용 근데 거리가 같다? 자기 손잡이 이용
// 순서대로 누를 번호가 담긴 배열 numbers 왼 오 손잡이인지 문자열은 hand
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function solution(numbers, hand) {
  let answer = "";
  let leftThumb = "*";
  let rightThumb = "#";

   // '맨해튼 거리' 라는 길이를 계산하는 함수.
   // '맨해튼 거리'는 직선거리가 아닌, 상하좌우만을 사용해서 계산하는 거리임
   // 한번 검색해서 확인하는게 나을듯 
   // '맨해튼 거리'를 사용한 이유는 키패드를 누를 때 상하좌우로만 움직일 수 있다는 조건이 있기 때문
   function getDistance(thumb, target) {
    const keypad = {
      1: [0, 0],
      2: [0, 1],
      3: [0, 2],
      4: [1, 0],
      5: [1, 1],
      6: [1, 2],
      7: [2, 0],
      8: [2, 1],
      9: [2, 2],
      0: [3, 1],
    };

    const thumbPos = keypad[thumb] || [3, 0]; // 키패드에서 없는 위치로 기본값 설정(엄지의 위치를 찾지 못한 경우)
    const targetPos = keypad[target]; // 대상 숫자의 키패드 상 위치 가져오기
    return (
      Math.abs(thumbPos[0] - targetPos[0]) +
      Math.abs(thumbPos[1] - targetPos[1])
    );
  };
  // 입력된 숫자 반복
  for (const num of numbers) {
    if (num === 1 || num === 4 || num === 7) { // 좌측에 있는지 확인
      answer += "L";
      leftThumb = num;
    } else if (num === 3 || num === 6 || num === 9) { // 우측에 있는지 확인
      answer += "R";
      rightThumb = num;
    } else { // 마지막으로 중앙에 있는지 확인(양 엄지에서 입력할 숫자까지의 거리 계산)
      const leftDistance = getDistance(leftThumb, num);
      const rightDistance = getDistance(rightThumb, num);
      // 거리와 키패드를 누를 손가락에 대한 조건을 기반으로 왼손, 오른손 중 어떤 손가락을 사용할 건지 결정
      if (
        leftDistance < rightDistance ||
        (leftDistance === rightDistance && hand === "left")
      ) {
        answer += "L";
        leftThumb = num;
      } else {
        answer += "R";
        rightThumb = num;
      }
    }
  }

  return answer;
}

Copy link
Collaborator

@CBWDG CBWDG Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

키패드 누르기는 진짜 너어어어어어어어무 길어서 그냥 제가 다시 풀어서 올려드렸어요.
생각보다 맨해튼 거리로 푼 사람들이 많더군요ㅋㅋ 궁금한거 있으면 바로 물어보시고, 길이(거리)를 구하는 문제는 프로그래머스에 "게임 맵 최단거리" 라는게 있는데 시간되면 한번 풀어보시길

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

나도 방금 풀어봤는데, 나보다 너가 더 잘푼듯하다
지금 프로그래머스에서 다른 사람들이 푼 거 보고 있는데 차라리 이걸 보는게 나을듯
나는 곽형조, 차현 이 두 분 풀이가 엄청 좋아보이네

@cyoure cyoure changed the title 김준우 코팅테스트 (다트게임) 김준우 코팅테스트 (계산기) Jan 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants