-1

我有一些学生的个人资料,其中包含物理、化学和数学等几个学科的价值观。我需要根据个人在科目上的分数找到一个优势学生的名单。例如:

let students = [{name: "A", phy: 70, chem: 80, math: 90},
              {name: "B", phy: 75, chem: 85, math: 60},
              {name: "C", phy: 78, chem: 81, math: 92},
              {name: "D", phy: 75, chem: 85, math: 55}]; 

如果一个学生满足以下两个条件,他将优于另一个学生。1. student_1 >= student_2 对于所有参数 2. student_1 > student_2 对于至少一个参数

我试过使用嵌套循环。可能是蛮力算法。我添加了另一个名为“passed”的参数来跟踪它是否优于其他参数。这是代码:


let students = [{ name: "A", phy: 70, chem: 80, math: 90, passed: true },
{ name: "B", phy: 75, chem: 85, math: 60, passed: true },
{ name: "C", phy: 78, chem: 81, math: 92, passed: true },
{ name: "D", phy: 75, chem: 85, math: 55, passed: true }];

let weak_student: any;

for (let student_1 of students) {

    if (student_1.passed == false ||
        students[students.length] === student_1) {
        continue;
    }

let compareList = students.filter(i => i.name != student_1.name && i.passed == true);

    for (let student_2 of compareList) {

        if ((student_1.phy >= student_2.phy &&
            student_1.chem >= student_2.chem &&
            student_1.math >= student_2.math)
            &&
            (student_1.phy > student_2.phy ||
                student_1.chem > student_2.chem ||
                student_1.math > student_2.math)
        ) {
            weak_student = students.find(i => i.name === student_2.name);
            weak_student.passed = false;

        } else if (student_1.phy < student_2.phy &&
            student_1.chem < student_2.chem &&
            student_1.math < student_2.math) {

            student_1.passed = false;
            break;
        }
    }
}
console.log(students);

我发现预期的结果是学生 A & D 的标志“通过”== false。现在我需要通过使用不同的算法(如分治法、最近邻法、分支定界法等)或任何其他有效方式来获得相同的结果。我需要比较大型数据集的时间和空间复杂度算法。

4

1 回答 1

1

[-1, 0, 1]您可以通过获取键对数组进行排序,获取所有值的增量并通过使用将值归一化,对值Math.sign求和并将此总和作为排序结果返回。

最高组是具有最大价值的组。

let students = [{ name: "A", phy: 70, chem: 80, math: 90 }, { name: "B", phy: 75, chem: 85, math: 60 }, { name: "C", phy: 78, chem: 81, math: 92 }, { name: "D", phy: 75, chem: 85, math: 55 }];

students.sort((a, b) => ['phy', 'chem', 'math']
    .map(k => Math.sign(b[k] - a[k]))
    .reduce((a, b) => a + b)
);

console.log(students);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2019-11-04T10:47:26.397 回答