【算法题】智能成绩表(js)

【算法题】智能成绩表(js)_第1张图片
【算法题】智能成绩表(js)_第2张图片
在这里插入图片描述
【算法题】智能成绩表(js)_第3张图片

总分相同按名字字典顺序。

解法:

function solution(lines) {
  const [personNum, subjectNum] = lines[0]
    .split(" ")
    .map((item) => parseInt(item));
  const subjects = lines[1].split(" ");
  const classMates = [];
  let results = [];
  for (let i = 2; i < 2 + personNum; i++) {
    const [name, yuwen, shuxue] = lines[i]
      .split(" ")
      .map((item, index) => (index > 0 ? parseInt(item) : item));
    classMates.push({
      name,
      yuwen,
      shuxue,
      all: yuwen + shuxue,
    });
  }

  const standard = lines[lines.length - 1];
  if (subjects.includes(standard)) {
    results = classMates
      .sort((a, b) => b[standard] - a[standard])
      .map((item) => item.name);
  } else {
    results = classMates.sort((a, b) => b.all - a.all).map((item) => item.name);
  }
  return results.join("\n");
}

console.log(
  solution([
    "3 2",
    "yuwen shuxue",
    "fangfang 95 90",
    "xiaohua 88 95",
    "minmin 100 82",
    "yuwen",
  ])
);
/* 
3 2
yuwen shuxue
fangfang 95 90
xiaohua 88 95
minmin 100 82
shuxue
=>
xiaohua fangfang minmin


3 2
yuwen shuxue
fangfang 95 90
xiaohua 88 95
minmin 100 82
zongfen
=> fangfang minmin xiaohua 

 */

你可能感兴趣的:(算法题,算法,javascript)