function solution(
friends, // 친구이름 배열
gifts // 선물기록 배열 "A B"
) {
let giftCost = {};
let giftInfo = {};
let maxGiftCnt = 0;
// cost 계산
friends.forEach((friend) => {
giftCost[friend] =
gifts.filter((item) => item.split(' ')[0] === friend).length -
gifts.filter((item) => item.split(' ')[1] === friend).length;
giftInfo[friend] = friends
.filter((item) => item !== friend)
.reduce((acc, value) => ({ ...acc, [value]: 0 }), {});
});
// 주고받은 선물 계산
Array.from(new Set(gifts)).forEach((gift) => {
const giftSplit = gift.split(' ');
const giftCnt = gifts.filter((item) => item === gift).length;
giftInfo[giftSplit[0]][giftSplit[1]] = giftCnt;
});
// 선물 수 계산
friends.forEach((myNm) => {
let myNextMonthGift = 0;
Object.keys(giftInfo[myNm]).forEach((friendNm) => {
if (giftInfo[myNm][friendNm] > giftInfo[friendNm][myNm]) {
// A가 B에게 준게 B가 A에게 준 것 보다 많으면 A에 선물 하나
myNextMonthGift += 1;
} else if (giftInfo[myNm][friendNm] === giftInfo[friendNm][myNm]) {
// A 와 B 가 주고받은 선물이 같을 때
if (giftCost[myNm] > giftCost[friendNm]) {
// 선물지수가 A가 높을 때 A에 선물 하나
myNextMonthGift += 1;
}
}
});
if (maxGiftCnt < myNextMonthGift) maxGiftCnt = myNextMonthGift;
});
return maxGiftCnt;
}
* 사용한 변수 콘솔 내용
giftCost >> { a: 0, b: 0, c: 0 }
giftInfo >> { a: { b: 1, c: 2 }, b: { a: 1, c: 0 }, c: { a: 2, b: 0 } }
maxGiftCnt >> 0
처음에 그냥 지문에 적힌대로 짜보자 하고 시간 생각 안한 코드...
보이기엔 초 심플하지만 시간복잡도는 n³ 정도..?? ㅎㅎㅎ 데이터는 가공하고 쓰자~
function solution(
friends, // 친구이름 배열
gifts // 선물기록 배열 "A B"
) {
let nextMonthGift = 0;
friends.map((myNm, idx) => {
let myNextMonthGift = 0;
// 친구 배열 돌림
friends.map((friend) => {
if (friend !== myNm) {
// 내가 A 친구 준거 찾음
const myGift = gifts.filter((item) => item === `${myNm} ${friend}`)?.length ?? 0;
// A친구 내가 준거 찾음
const friendGift = gifts.filter((item) => item === `${friend} ${myNm}`)?.length ?? 0;
if (myGift > friendGift) {
myNextMonthGift += 1;
} else if (myGift === friendGift) {
// 내가 준거
const myGiveGift = gifts.filter((item) => item.split(' ')[0] === myNm).length;
// 내가 받은거
const myGetGift = gifts.filter((item) => item.split(' ')[1] === myNm).length;
// 친구가 준거
const friendGiveGift = gifts.filter((item) => item.split(' ')[0] === friend).length;
// 친구가 받은거
const friendGetGift = gifts.filter((item) => item.split(' ')[1] === friend).length;
if (myGiveGift - myGetGift > friendGiveGift - friendGetGift) myNextMonthGift += 1;
}
if (nextMonthGift < myNextMonthGift) nextMonthGift = myNextMonthGift;
}
})
})
return nextMonthGift;
}
반응형
'🔥 Javascript > 🔸 알고리즘' 카테고리의 다른 글
Javascript) 공원산책 (0) | 2024.10.11 |
---|---|
Javascript ) 프로그래머스 - [PCCP 기출문제] 1번 / 붕대 감기 (0) | 2024.09.22 |
Javscript ) 프로그래머스 - [PCCP 기출문제] 1번 / 동영상 재생기 (0) | 2024.09.21 |
JavaScript) 프로그래머스 가장 가까운 같은 글자 (0) | 2023.02.01 |
JavaScript) 프로그래머스 크기가 작은 부분문자열 (0) | 2023.01.29 |