๐Ÿ’ฏ CodingTest/Programmers

[Programmers] (Javascript) ๋ฉ”๋‰ด ๋ฆฌ๋‰ด์–ผ

S.Honey 2022. 4. 28. 16:00

https://programmers.co.kr/learn/courses/30/lessons/72411?language=javascript# 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ฉ”๋‰ด ๋ฆฌ๋‰ด์–ผ

๋ ˆ์Šคํ† ๋ž‘์„ ์šด์˜ํ•˜๋˜ ์Šค์นดํ”ผ๋Š” ์ฝ”๋กœ๋‚˜19๋กœ ์ธํ•œ ๋ถˆ๊ฒฝ๊ธฐ๋ฅผ ๊ทน๋ณตํ•˜๊ณ ์ž ๋ฉ”๋‰ด๋ฅผ ์ƒˆ๋กœ ๊ตฌ์„ฑํ•˜๋ ค๊ณ  ๊ณ ๋ฏผํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ธฐ์กด์—๋Š” ๋‹จํ’ˆ์œผ๋กœ๋งŒ ์ œ๊ณตํ•˜๋˜ ๋ฉ”๋‰ด๋ฅผ ์กฐํ•ฉํ•ด์„œ ์ฝ”์Šค์š”๋ฆฌ ํ˜•ํƒœ๋กœ ์žฌ๊ตฌ์„ฑํ•ด์„œ

programmers.co.kr

 

โ–ถ ์ฝ”๋“œ : 

 

function solution(orders, course) 
{
    let answer = [];
    let data = new Map();
    
    for (const order of orders)
    {
        let orderToArr = [...order];
        orderToArr = orderToArr.sort();
        for (let i = order.length; i>0; i--)
        {
            let combinations = combination(orderToArr, i);
            for (let c of combinations)
            {
                c = c.join('');
                data.set(c, data.get(c) + 1 || 1);
            }
        }
    }

    data = [...data].sort((a,b) => b[1] - a[1]);

    for (const num of course)
    {
        maxNum = 2
        for (const e of data)
        {
            if (e[0].length === num)
            {
                if (e[1] >= maxNum){
                    answer.push(e[0]);
                    maxNum = e[1]
                }
            }
        }
    }
    answer = answer.sort();
    return answer;
}


const combination = function (arr, selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((value) => [value]);
  
    arr.forEach((fixed, index, origin) => {
      const rest = origin.slice(index + 1); 
      const temp = combination(rest, selectNumber - 1);
      const attached = temp.map((e) => [fixed, ...e]);
      results.push(...attached);
    });
    return results;
  }

 

โ–ถ ๋ฌธ์ œํ’€์ด : 

1. ์œ„ ๋ฌธ์ œ๋Š” ์กฐํ•ฉ(Combination)์„ ์ด์šฉํ•ด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค. 

2. ๊ธฐ์กด ์‚ฌ์šฉํ•˜๋˜ Python์˜ ๊ฒฝ์šฐ itertools์— ๋‚ด์žฅ๋œ combination ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋˜์—ˆ์ง€๋งŒ JS์˜ ๊ฒฝ์šฐ์—๋Š” ์ง์ ‘ ๊ตฌํ˜„ํ•ด์„œ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๋‹ค. ์ธํ„ฐ๋„ท์˜ ๋„์›€์„ ๋ฐ›์•„ ์ˆœ์—ด๊ณผ ์กฐํ•ฉ ๊ด€๋ จํ•˜์—ฌ ํ•จ์ˆ˜๋ฅผ ์งœ๋†“์œผ์‹  ๋ถ„์ด ๊ณ„์…”์„œ ๋‚ด์šฉ์„ ์ž˜ ์ฝ๊ณ  ์ ์šฉํ•˜์˜€๋‹ค. 

3. ๊ทธ ์™ธ์˜ ์ฝ”๋“œ๋Š” ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•œ๋Œ€๋กœ ๊ตฌํ˜„ํ•˜๋Š” ๊ณผ์ •์ด์—ˆ๊ธฐ์— ํฌ๊ฒŒ ์–ด๋ ต์ง€ ์•Š์•˜๋‹ค.