Algorithm/Programmers

[JavaScript] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์‹คํŒจ์œจ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 9. 5. 18:01

[๋ฌธ์ œ]

https://school.programmers.co.kr/learn/courses/30/lessons/42889

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ’€์ด]

1. level ๋ฐฐ์—ด์— ํ˜„์žฌ ์Šคํ…Œ์ด์ง€(๋ ˆ๋ฒจ)์— ๋„๋‹ฌํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

2. clear ๋ณ€์ˆ˜์— ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ๊นŒ์ง€ ํด๋ฆฌ์–ดํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜๋ฅผ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

  • ๋งˆ์ง€๋ง‰ ๋ ˆ๋ฒจ๊นŒ์ง€ ํด๋ฆฌ์–ดํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜ = level[N+1]

3. fail ๋ฐฐ์—ด์— [์Šคํ…Œ์ด์ง€, ์Šคํ…Œ์ด์ง€ ์‹คํŒจ์œจ] ํ˜•ํƒœ๋กœ ๋ชจ๋“  ์Šคํ…Œ์ด์ง€์˜ ์‹คํŒจ์œจ์„ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

  • ๋งŒ์•ฝ ํ˜„์žฌ ์Šคํ…Œ์ด์ง€๊ฐ€ i๋ผ๋ฉด, ์‹คํŒจ์œจ = (ํ˜„์žฌ ์Šคํ…Œ์ด์ง€์— ์žˆ๋Š” ํ”Œ๋ ˆ์ด์–ด ์ˆ˜) / (i~N+1 ๊นŒ์ง€ ๋„๋‹ฌํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜์˜ ํ•ฉ)
  • level ๋ฐฐ์—ด์„ N๋ถ€ํ„ฐ 1๊นŒ์ง€ ์Šคํ…Œ์ด์ง€๋ฅผ ํ•œ๋‹จ๊ณ„์”ฉ ๋‚ฎ์ถ”์–ด ๊ฐ€๋ฉฐ clear ๋ณ€์ˆ˜๋ฅผ ๋”ํ•ด ์—ฐ์‚ฐ์„ ์ตœ์†Œํ™”

๋”ฐ๋ผ์„œ ์ž…์ถœ๋ ฅ ์˜ˆ 1๋ฒˆ์˜ fail ๋ฐฐ์—ด์„ ๊ณ„์‚ฐํ•œ ๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

[
  [ 5, 0 ],
  [ 4, 0.5 ],
  [ 3, 0.5 ],
  [ 2, 0.42857142857142855 ],
  [ 1, 0.125 ]
]

4. ๋งˆ์ง€๋ง‰์œผ๋กœ sort ์—ฐ์‚ฐ์„ ํ†ตํ•ด fail ๋ฐฐ์—ด์„ ์‹คํŒจ์œจ์ด ๋†’์€ ์Šคํ…Œ์ด์ง€ ๋ถ€ํ„ฐ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ answer์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.

fail.sort((a, b) => a[1] === b[1] ? a[0] - b[0] : b[1] - a[1]);

fail.forEach(([a, b]) => answer.push(a));

 

[์ฝ”๋“œ]

function solution(N, stages) {
    var answer = [];
    
    const level = Array.from({length: N+2}, () => 0);
    
    stages.forEach((num) => {
        level[num]++;
    })
    
    // [๋ ˆ๋ฒจ, ์‹คํŒจ์œจ]
    const fail = [];
    let clear = level[N+1];
    
    for(let i=N;i>=1;i--) {
        clear += level[i];
        clear === 0 ? fail.push([i, 0]) : fail.push([i, level[i]/clear]);
    }
    
    fail.sort((a, b) => a[1] === b[1] ? a[0] - b[0] : b[1] - a[1]);
    
    fail.forEach(([a, b]) => answer.push(a));

    return answer;
}