https://school.programmers.co.kr/learn/courses/30/lessons/258712
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이
function solution(friends, gifts) {
let giftCountReceived = {};
let giftCountGiven = {};
// 친구들 값들을 초기화
friends.forEach(friend => {
giftCountGiven[friend] = {};
giftCountReceived[friend] = 0;
friends.forEach(other => {
giftCountGiven[friend][other] = 0; // 초기 선물 수는 0
});
});
// Json 형태로 각각 누가 누구 한테 줬는지 및 받은 결과 값
gifts.forEach((v,i) => {
const [giver, receives] = v.split(/\s+/);
giftCountGiven[giver][receives] += 1;
giftCountReceived[receives] += 1 ;
});
// 친구들한테 준 값 배열로 표시
let giftForFriendArray = [];
for (let key in giftCountGiven) {
let giftForFriends = 0;
friends.forEach((v) => {
giftForFriends += giftCountGiven[key][v];
})
giftForFriendArray.push(giftForFriends)
}
// 각각 누구한테 줬는지 배열로 표시
let giftCountGivenArray = [];
for( let key in giftCountGiven) {
let arrayGift = [];
friends.forEach( (v) => {
arrayGift.push(giftCountGiven[key][v])
})
giftCountGivenArray.push(arrayGift)
}
// 받은 결과값 배열로 표시
let giftCountReceivedArray = [];
for( let key in giftCountReceived) {
giftCountReceivedArray.push(giftCountReceived[key])
}
// 선물 지수 표시
let giftIndex = [];
for ( let idx in giftCountReceivedArray ) {
giftIndex.push( giftForFriendArray[idx] - giftCountReceivedArray[idx] );
}
let giftsNextMonth = new Array(friends.length).fill(0);
// 다음 달 받을 선물 계산
for ( let idx =0; idx < friends.length; idx++) {
for ( let j = idx +1; j < friends.length ; j++ ) {
if (idx === j) {
continue
}
if ( giftCountGivenArray[idx][j] > giftCountGivenArray[j][idx] ) {
giftsNextMonth[idx] += 1 ;
}
if ( giftCountGivenArray[idx][j] < giftCountGivenArray[j][idx] ) {
giftsNextMonth[j] += 1 ;
}
if ( giftCountGivenArray[idx][j] === giftCountGivenArray[j][idx] ) {
if (giftIndex[idx] > giftIndex[j]) {
giftsNextMonth[idx] += 1;
} else if (giftIndex[idx] < giftIndex[j]) {
giftsNextMonth[j] += 1;
}
}
}
}
// 최댓값 반환
return Math.max(...giftsNextMonth)
}
const friends = ["muzi", "ryan", "frodo", "neo"]
const gifts = ["muzi frodo", "muzi frodo", "ryan muzi", "ryan muzi", "ryan muzi", "frodo muzi",
"frodo ryan", "neo muzi"]
console.log(solution(friends, gifts))
https://github.com/alsyean/algorithm/blob/master/lv1/most_received_gift.js
algorithm/lv1/most_received_gift.js at master · alsyean/algorithm
coding test algorithm. Contribute to alsyean/algorithm development by creating an account on GitHub.
github.com
출처 : 프로그래머스 코딩테스트 연습, https://school.programmers.co.kr/learn/challenges
코딩테스트 연습 | 프로그래머스 스쿨
개발자 취업의 필수 관문 코딩테스트를 철저하게 연습하고 대비할 수 있는 문제를 총망라! 프로그래머스에서 선발한 문제로 유형을 파악하고 실력을 업그레이드해 보세요!
school.programmers.co.kr
'코딩테스트' 카테고리의 다른 글
[프로그래머스] 신고 결과 받기 / js (0) | 2024.04.19 |
---|---|
[프로그래머스 ] 추억의 점수 / Js (0) | 2024.04.19 |