► JS Algorithm/Programmers

[Programmers] JavaScript 알고리즘 | Lv.0 등수 매기기

다람트리 2024. 9. 9. 22:50
반응형

🔒 문제 설명

영어 점수와 수학 점수의 평균 점수를 기준으로 학생들의 등수를 매기려고 합니다. 영어 점수와 수학 점수를 담은 2차원 정수 배열 score 주어질 , 영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 return하도록 solution 함수를 완성해주세요.


🔒 제한사항 

  • 0 ≤ score[0], score[1] ≤ 100
  • 1 ≤ score의 길이 ≤ 10
  • score의 원소 길이는 2입니다.
  • score 중복된 원소를 갖지 않습니다.

🔒 입출력 예

score result
[[80, 70], [90, 50], [40, 70], [50, 80]] [1, 2, 4, 3]
[[80, 70], [70, 80], [30, 50], [90, 100], [100, 90], [100, 100], [10, 30]] [4, 4, 6, 2, 2, 1, 7]

🔒 입출력 예 설명

입출력 예 #1

  • 평균은 각각 75, 70, 55, 65 이므로 등수를 매겨 [1, 2, 4, 3]을 return합니다.

입출력 예 #2

  • 평균은 각각 75, 75, 40, 95, 95, 100, 20 이므로 [4, 4, 6, 2, 2, 1, 7] 을 return합니다.
  • 공동 2등이 , 공동 4등이 2 이므로 3등과 5등은 없습니다.

 

🔐 GPT's solution

Array.prototype.map()

Array.prototype.sort()

Array.prototype.indexOf()

function solution(score) {
  const average = score.map(([eng, math]) => (eng + math) / 2);
  const sorted = [...average].sort((a, b) => b - a);

  return console.log(average.map((avg) => sorted.indexOf(avg) + 1));
}

solution([
  [80, 70],
  [90, 50],
  [40, 70],
  [50, 80],
]); //expected output: [1, 2, 4, 3]
solution([
  [80, 70],
  [70, 80],
  [30, 50],
  [90, 100],
  [100, 90],
  [100, 100],
  [10, 30],
]); //expected output: [4, 4, 6, 2, 2, 1, 7]

 

🔐 solution of others

Array.prototype.map()

Array.prototype.filter()

function solution(score) {
  return console.log(
    score.map((el) => {
      return (
        score.filter((v) => (v[0] + v[1]) / 2 > (el[0] + el[1]) / 2)
          .length + 1
      );
    })
  );
}

solution([
  [80, 70],
  [90, 50],
  [40, 70],
  [50, 80],
]); //expected output: [1, 2, 4, 3]
solution([
  [80, 70],
  [70, 80],
  [30, 50],
  [90, 100],
  [100, 90],
  [100, 100],
  [10, 30],
]); //expected output: [4, 4, 6, 2, 2, 1, 7]

🔐 solution of others

Array.prototype.push()

function solution(score) {
  const answer = [];
  for (let [a, b] of score) {
    const ab = (a + b) / 2;
    let cnt = 1;
    for (let [aa, bb] of score) {
      const aabb = (aa + bb) / 2;
      if (aabb > ab) cnt++;
    }
    answer.push(cnt);
  }
  return console.log(answer);
}

solution([
  [80, 70],
  [90, 50],
  [40, 70],
  [50, 80],
]); //expected output: [1, 2, 4, 3]
solution([
  [80, 70],
  [70, 80],
  [30, 50],
  [90, 100],
  [100, 90],
  [100, 100],
  [10, 30],
]); //expected output: [4, 4, 6, 2, 2, 1, 7]

 


 

반응형