Scala 练习
Scala 练习
统计总分年级排名前十学生各科的分数
package com.shujia.scala
import scala.io.{BufferedSource, Source}
object Demo35Student {
def main(args: Array[String]): Unit = {
/**
* 统计总分年级排名前十学生各科的分数
*
* 1、统计每个学生的总分
*
* 2、按总分排名
*
* 3、取前十的学生
*
* 4、关联获取学生各科的分数
*
*/
//1、读取分数表
val source: BufferedSource = Source.fromFile("data/score.txt")
val scores: List[String] = source.getLines().toList
//2、取出学号和分数
val idAndScore: List[(String, Double)] = scores.map(s => {
val split: Array[String] = s.split(",")
(split(0), split(2).toDouble)
})
//3、按学生分组
val scoreGroup: Map[String, List[(String, Double)]] = idAndScore.groupBy(kv => kv._1)
//4、计算学生的总分
val idSumScore: Map[String, Double] = scoreGroup.map {
case (id: String, scoAndIds: List[(String, Double)]) =>
//计算学生的总分
val scos: List[Double] = scoAndIds.map(kv => kv._2)
val sumScore: Double = scos.sum
//返回数据
(id, sumScore)
}
//将map转换成list
val sumScoreList: List[(String, Double)] = idSumScore.toList
//5、按照总分降序排序
val sortSumScore: List[(String, Double)] = sumScoreList.sortBy(kv => -kv._2)
//6、取前十
val top10: List[(String, Double)] = sortSumScore.take(10)
//7、取出前十学生的学号
val top10Ids: List[String] = top10.map(kv => kv._1)
//8、取出前十学生各科的分数
val top10Student: List[String] = scores.filter(sco => {
val id: String = sco.split(",")(0)
top10Ids.contains(id)
})
top10Student.foreach(println)
}
}
统计偏科最严重的前100名学生
package com.shujia.scala
import scala.io.{BufferedSource, Source}
object Demo36Student {
def main(args: Array[String]): Unit = {
/**
* 统计偏科最严重的前100名学生
*
*/
//1、读取文件
val source: BufferedSource = Source.fromFile("data/score.txt")
val scores: List[String] = source.getLines().toList
//2、取出学号和分数
val idAndScore: List[(String, Double)] = scores.map(sco => {
val split: Array[String] = sco.split(",")
val id: String = split(0)
val score: Double = split(2).toDouble
(id, score)
})
//3、按照学号分组
val groupBy: Map[String, List[(String, Double)]] = idAndScore.groupBy(kv => kv._1)
//4、计算方差
val result: List[(String, List[(String, Double)], Double)] = groupBy
.toList
.map {
case (id: String, idAndSco: List[(String, Double)]) =>
//取出学生各科的分数
val scores: List[Double] = idAndSco.map(kv => kv._2)
//计算平均值
val avg: Double = scores.sum / scores.length
//带入公式计算方差
val std: Double = scores.map(sco => (sco - avg) * (sco - avg)).sum / scores.length
//返回数据
(id, idAndSco, std)
}
//5、按照方差排序
val sort: List[(String, List[(String, Double)], Double)] = result.sortBy(kv => -kv._3)
//6、取前100
val top100: List[(String, List[(String, Double)], Double)] = sort.take(100)
top100.foreach(println)
}
}