如何在列表中找到成绩最好的学生? [英] How to find students with the best grades in a list?

查看:82
本文介绍了如何在列表中找到成绩最好的学生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我有一个Students列表. Students具有诸如namebirth dategrade等的字段.如何在Scala中找到具有最佳gradeStudents?

Suppose, I have a list of Students. Students have fields like name, birth date, grade, etc. How would you find Students with the best grade in Scala?

例如:

List(Student("Mike", "A"), Student("Pete", "B"), Student("Paul", A))"

我想得到

List(Student("Mike", "A"), Student("Paul", A))

很明显,我可以找到max grade(在上面的列表中为"A"),然后找到filter列表

Obviously, I can find the max grade ("A" in the list above) and then filter the list

students.filter(_.grade == max_grade)

此解决方案是O(N),但在列表上运行了两次.您能提出更好的解决方案吗?

This solution is O(N) but runs over the list twice. Can you suggest a better solution?

推荐答案

在列表上运行两次可能是最好的方法,但是如果您 insist 只能运行一次以上的解决方案,您可以使用折叠(此处适用于空列表):

Running over the list twice is probably the best way to do it, but if you insist on a solution that only runs over once, you can use a fold (here works on empty lists):

(List[Student]() /: list){ (best,next) => best match {
  case Nil => next :: Nil
  case x :: rest =>
    if (betterGrade(x,next)) best
    else if (betterGrade(next,x)) next :: Nil
    else next :: best
}}

如果您不熟悉褶皱,请在答案的此处中进行描述.当您通过集合(例如列表)时,它们是积累某些东西的一般方法.如果您不熟悉匹配,则可以使用isEmptyhead做同样的事情.如果希望学生按照与原始列表中出现的顺序相同的顺序,请在最后运行.reverse.

If you are unfamiliar with folds, they are described in an answer here. They're a general way of accumulating something as you pass over a collection (e.g. list). If you're unfamiliar with matching, you can do the same thing with isEmpty and head. If you want the students in the same order as they appeared in the original list, run .reverse at the end.

这篇关于如何在列表中找到成绩最好的学生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆