# [Algorithm/JS] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 42889 ์‹คํŒจ์œจ

๐Ÿ”— ๋ฌธ์ œ ๋ฐ”๋กœ๊ฐ€๊ธฐ (opens new window)

# Solution

function solution(N, stages) {
  let answer = [];

  for (let i = 1; i <= N; i++) {
    let arrive = stages.filter((a) => a >= i).length; // ๋„๋‹ฌํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
    let noPass = stages.filter((a) => a === i).length; // ๋„๋‹ฌํ–ˆ์ง€๋งŒ ํ†ต๊ณผํžˆ์ง€ ๋ชปํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
    let rate = noPass / arrive; // ์‹คํŒจ์œจ
    answer.push([i, rate]);
  }

  answer.sort((a, b) => {
    if (a[1] === b[1]) a[0] - b[0];
    return b[1] - a[1];
  });

  answer.forEach((a, i) => (answer[i] = a[0]));
  return answer;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# ํ’€์ด ์„ค๋ช…

arrive : i ๋ฒˆ ์Šคํ…Œ์ด์ง€์— ๋„๋‹ฌํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
noPass: i ๋ฒˆ ์Šคํ…Œ์ด์ง€์— ๋„๋‹ฌํ–ˆ์ง€๋งŒ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
rate: ์‹คํŒจ์œจ (noPass / arrive)

for ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ์Šคํ…Œ์ด์ด์ง€ ์ˆ˜๋งŒํผ ๋ฐ˜๋ณตํ•œํ•˜์—ฌ ๊ฐ ์Šคํ…Œ์ด์ง€์˜ ์‹คํŒจ์œจ์„ ๊ณ„์‚ฐํ•œ๋‹ค. [์Šคํ…Œ์ด์ง€๋ฒˆํ˜ธ, ์‹คํŒจ์œจ] ์„ answer ์— push ํ•œ๋‹ค

์‹คํŒจ์œจ์— ๋”ฐ๋ผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์•ผํ•œ๋‹ค. sort ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•  ์ ์€ ์‹คํŒจ์œจ์ด ๊ฐ™์„ ๊ฒฝ์šฐ ์Šคํ…Œ์ด์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ ๋ถ€ํ„ฐ ์ •๋ ฌํ•œ๋‹ค.

answer.sort((a, b) => {
  if (a[1] === b[1]) a[0] - b[0];
  return b[1] - a[1];
});
1
2
3
4

๊ฐ ๋ฐฐ์—ด์— [์Šคํ…Œ์ด์ง€ ๋ฒˆํ˜ธ, ์‹คํŒจ์œจ] ํ˜•ํƒœ๋กœ ์ €์žฅ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์œ„์™€ ๊ฐ™์ด ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋‹ค.

์‹คํŒจ์œจ์ด ๊ฐ™์„ ๊ฒฝ์šฐ ์Šคํ…Œ์ด์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ž‘์€ ๊ฒƒ์œผ๋กœ ์ •๋ ฌ
if (a[1] === b[1]) a[0] - b[0];

์‹คํŒจ์œจ์ด ํฐ ๊ฒƒ๋ถ€ํ„ฐ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
return b[1] - a[1];

answer.forEach((a, i) => (answer[i] = a[0]));
return answer;
1
2

๊ฐ ๋ฐฐ์—ด์„ ์ˆœํ™˜ํ•˜๋ฉด์„œ ์Šคํ…Œ์ด์ง€ ๋ฒˆํ˜ธ(a[0])๋กœ ๋ฎ์–ด์“ด๋‹ค.

# ๋‚ด์šฉ ์ถ”๊ฐ€

์•„๋ž˜์™€ ๊ฐ™์ด ์ •๋ ฌํ•  ๋•Œ ์‹คํŒจ์œจ์ด ๊ฐ™๋‹ค๋ฉด ์Šคํ…Œ์ด์ง€๊ฐ€ ์ž‘์€ ๊ฒƒ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ๊ณผ์ •์€ ์‚ฌ์‹ค ํ•„์š” ์—†๋Š” ๊ณผ์ •์ด์—ˆ๋‹ค..

answer.sort((a, b) => {
  if (a[1] === b[1]) a[0] - b[0]; // * ์‚ญ์ œํ•ด์•ผ ํ•  ์ฝ”๋“œ
  return b[1] - a[1];
});
1
2
3
4

์ด์œ ๋Š” ์ด๋ฏธ ์‹คํŒจ์œจ์„ ๊ณ„์‚ฐํ•˜๊ณ  answer ์— pushํ•˜๋Š” ๊ณผ์ •์—์„œ ์ด๋ฏธ ์ฒซ๋ฒˆ์งธ ์Šคํ…Œ์ด์ง€๋ถ€ํ„ฐ ์ฐจ๋ก€๋กœ push ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

for (let i = 1; i <= N; i++) {
  let arrive = stages.filter((a) => a >= i).length; // ๋„๋‹ฌํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
  let noPass = stages.filter((a) => a === i).length; // ๋„๋‹ฌํ–ˆ์ง€๋งŒ ํ†ต๊ณผํžˆ์ง€ ๋ชปํ•œ ํ”Œ๋ ˆ์ด์–ด ์ˆ˜
  let rate = noPass / arrive; // ์‹คํŒจ์œจ
  answer.push([i, rate]);
}
1
2
3
4
5
6
Last Updated: 2022. 6. 5. ์˜คํ›„ 3:42:39