scala经典函数练习题及答案,做完对集合的理解更上一层楼

scala经典函数练习题及答案,做完对集合的理解更上一层楼scala 经典函数练习题及答案 练习题目 1 编写函数 values fun Int gt Int low Int hight Int 该函数输出一个集合 对应给定区间内给定的给定函数的输入和输出 R 比如 values x gt x x 5 5 应该产出一个对偶集合 5 25

大家好,我是讯享网,很高兴认识大家。

scala经典函数练习题及答案

练习题目1

编写函数values(fun:(Int)=>Int,low:Int,hight:Int)
该函数输出一个集合,对应给定区间内给定的给定函数的输入和输出,R比如values(x=>x*x,-5,5)
应该产出一个对偶集合(-5,25),(-4,16),(-3,9)…(5,25)

练习题目2

如何使用reduceLeft函数得到数组中的最大元素

练习题目3

用to和reduceLeft实现阶乘函数,不得使用循环或者递归

练习题目4

编写函数largest(fun:(Int)=>Int,inputs:Seq[Int]),
输出在给定输入序列中给定函数的最大值。
举例来说,largest(x=>10x-xx,1 to 10)应该返回25.不得使用循环或递归

练习题目5

练习题目6

要得到一个序列的对偶很容易,比如:
var pairs = (1 to 10) zip (11 to 20)
假定你想要对这个序列做某中操作—比如,给对偶中的值求和,但是你不能直接使用:
pairs.map(_ + )
函数
+ _ 接受两个Int作为参数,而不是(Int,Int)对偶。
编写函数adjustToPair,该函数接受一个类型为(Int,Int)=>Int的函数作为参数,
并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_ * _)((6,7))应得到42。
然后用这个函数通过map计算出各个对偶的元素之和
柯里化的参数列表

练习题目7

做出一个对该方法的调用,让它帮我们判断某个字符串数组里的所有元素的长度是否和某个给定的整数数组相对应

练习题目8

题目需求,将a,b经过f1或者f2函数的结果作为 线性函数的y = kx的 k值,
返回线性函数y=k
x


讯享网

练习题目9

练习题目10

​ 数据如下 :每个字母代表一个人 , 统计任意一个人和其他人的共同好友

A:B,C,D,F,E,O B:A,C,E,K C:F,A,D,I D:A,E,F,L E:B,C,D,M,L F:A,B,C,D,E,O,M G:A,C,D,E,F H:A,C,D,E,O I:A,O J:B,O K:A,C,D L:D,E,F M:E,F,G O:A,H,I,J 

讯享网

练习题目11

讯享网user.txt uid , name , age , friend u001,hls,22,fengjie u002,wangwu,31,lisi u003,zhangyanru,22,tananpengyou u004,laocao,26,fengyi u005,mengqi,12,nvmengqi u006,haolei,38,sb u007,wanghongjing,24,wife u009,wanghongjing,24,wife 
order.txt oid,uid,cost order011,u001,300 order012,u002,200 order023,u006,100 order056,u007,300 order066,u003,500 order055,u004,300 order021,u005,300 order014,u001,100 order025,u005,300 order046,u007,30 order067,u003,340 order098,u008,310 

练习题目12

​ 数据如下: 统计线段在每个点重叠的次数 , 并按照从高到低排序输出

讯享网1,4 2,5 4,6 2,4 3,6 4,6 1,5 

练习题目13

site1,user1,2018-03-01 02:12:22 site1,user2,2018-03-05 04:12:22 site1,user2,2018-03-05 04:13:22 site1,user2,2018-03-05 04:14:22 site1,user2,2018-03-05 04:15:22 site4,user7, site1,user2,2018-03-05 05:15:22 site1,user2,2018-03-05 08:15:22 site1,user3,2018-03-05 04:15:22 site1,user4,2018-03-05 05:15:22 site1,user3,2018-03-07 11:12:22 site1,user3,2018-03-08 11:12:22 site2,user4,2018-03-07 15:12:22 site3,user5,2018-03-07 08:12:22 site3,user6,2018-03-05 08:12:22 site1,user1,2018-03-08 11:12:22 site1,,2018-03-08 11:12:22 site2,user2,2018-03-07 15:12:22 site3,user5,2018-03-07 08:12:22 site3,user5,2018-03-07 18:12:22 site3,user6,2018-03-05 08:12:22 site4,user7,2018-03-03 10:12:22 site2,,2018-03-08 11:12:22 site3,user5,2018-03-07 08:12:22 site3,user6,2018-03-05 08:12:22 site4,user5,2018-03-03 10:12:22 site4,user7,2018-02-20 11:12:22 

练习题目14

​ 统计文本文件中单词出现的次数 wordcount,并取出出现次数最多的前五个单词

article.txt

讯享网There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to bebecause you have only one life and one chance to do all the things you want to do May you have enough happiness to make you sweetenough trials to make youstrongenough sorrow to keep you humanenough hope to make you happy? Always put yourself in others’shoes If you feel that it hurts youit probably hurts the other person too The happiest of people don’t necessarily have the best of everything;they just make the most of everything that comes along their way Happiness lies for those who crythose who hurt those who have searchedand those who have triedfor only they can appreciate the importance of people who have touched their lives Love begins with a smilegrows with a kiss and ends with a tear The brightest future will always be based on a forgotten past you can’t go on well in lifeuntil you let go of your past failures and heartaches When you were bornyou were crying and everyone around you was smiling Live your life so that when you dieyou're the one who is smiling and everyone around you is crying Please send this message to those people who mean something to youto those who have touched your life in one way or anotherto those who make you smile when you really need itto those that make you see the brighter side of things when you are really downto those who you want to let them know that you appreciate their friendship And if you don’t don’t worrynothing bad will happen to youyou will just miss out on the opportunity to brighten someone’s day with this message 

答案:

题目一:

/* 练习题目1 编写函数values(fun:(Int)=>Int,low:Int,hight:Int) 该函数输出一个集合,对应给定区间内给定的给定函数的输入和输出,R比如values(x=>x*x,-5,5) 应该产出一个对偶集合(-5,25),(-4,16),(-3,9)...(5,25) */ object question01 { 
    def main(args: Array[String]): Unit = { 
    val array: Array[Int] = Array(-1, -3, 4, 6) def fun(array:Array[Int]):Array[(Int,Int)]={ 
    array.map{ 
    i=> (i,i*i) } } val array1: Array[(Int, Int)] = fun(array) println(array1.mkString(",")) } } 

题目二:

讯享网/* 练习题目2 如何使用reduceLeft函数得到数组中的最大元素 */ object question02 { 
    def main(args: Array[String]): Unit = { 
    val array: Array[Int] = Array(-1, -3, 4, 6) val i: Int = array.reduceLeft(Math.max) println(s"i = ${i}") } } 

题目三:

/* 练习题目3 用to和reduceLeft实现阶乘函数,不得使用循环或者递归 */ object question03 { 
    def main(args: Array[String]): Unit = { 
    def fun(i:Int):Int={ 
    val range: Range = i to 1 by -1 println(range.mkString(",")) range.reduceLeft(_*_) } println(fun(6)) } } 

题目四:

讯享网/* 练习题目4 编写函数largest(fun:(Int)=>Int,inputs:Seq[Int]), 输出在给定输入序列中给定函数的最大值。 举例来说,largest(x=>10*x-x*x,1 to 10)应该返回25.不得使用循环或递归 */ object question04 { 
    def main(args: Array[String]): Unit = { 
    def largest(fun: Int => Int, inputs: Seq[Int]):Int={ 
    inputs .map(fun(_)).max } val res: Int = largest(x => 10 * x - x * x, 1 to 10) println(s"res = ${res}") } } 

题目五:

/* 练习题目5 修改前一个函数,返回最大的输出对应的输入。 举例来说,largestAt(fun:(Int)=>Int,inputs:Seq[Int])应该返回5。不得使用循环或递归 */ object question05 { 
    def main(args: Array[String]): Unit = { 
    def largest(fun: Int => Int, inputs: Seq[Int]): Int = { 
    val seq: Seq[Int] = inputs.map(fun(_)) seq.find(_ == seq.max).getOrElse(-1) } val res: Int = largest(x => 10 * x - x * x, 1 to 10) println(s"res = ${res}") } } 

题目六:

讯享网/* 练习题目6 要得到一个序列的对偶很容易,比如: var pairs = (1 to 10) zip (11 to 20) 假定你想要对这个序列做某中操作—比如,给对偶中的值求和,但是你不能直接使用: pairs.map(_ + _) 函数_ + _ 接受两个Int作为参数,而不是(Int,Int)元组。 编写函数adjustToPair,该函数接受一个类型为(Int,Int)=>Int的函数作为参数, 并返回一个等效的, 可以以对偶作为参数的函数。举例来说就是:adjustToPair(_ * _)((6,7))应得到42。 然后用这个函数通过map计算出各个对偶的元素之和 柯里化的参数列表 */ object question06 { 
    def main(args: Array[String]): Unit = { 
    val pairs: immutable.Seq[(Int, Int)] = (1 to 10) zip (11 to 20) def adjustToPair(fun: (Int, Int) => Int)(tuple: (Int, Int)): Int = { 
    fun(tuple._1, tuple._2) } val result: Int = pairs.map { 
    t => adjustToPair(_ * _)(t) }.sum println(s"result = ${result}") } } 

题目七:

/* 练习题目7 做出一个对该方法的调用,让它帮我们判断某个字符串数组里的所有元素的长度是否和某个给定的整数数组相对应 */ object question07 { 
    def main(args: Array[String]): Unit = { 
    def check(strArr: Array[String], intArr: Array[Int]): Boolean = { 
    if (strArr.length != intArr.length) { 
    false } else { 
    for (i <- strArr.indices) { 
    if (strArr(i).length != intArr(i)) { 
    return false } } true } } //val strArr: Array[String] = Array[String]("a", "ab", "abc") val strArr: Array[String] = Array[String]("a", "ab", "abcd") val intArr: Array[Int] = Array[Int](1, 2, 3) println(check(strArr, intArr)) } } 

题目八:

讯享网/* 练习题目8 题目需求,将a,b经过f1或者f2函数的结果作为 线性函数的y = k*x的k值, 返回线性函数y=k*x */ object question08 { 
    def main(args: Array[String]): Unit = { 
    def fun2(a: Int, b: Int)(fun1:(Int,Int)=>Int): (Int) => Int = { 
    val k: Int = fun1(a, b) println(s"y=$k*x") k*_ } val function: Int => Int = fun2(1, 2)(_ + _) } } 

题目九:

/* 练习题目9 1.编写一个方法,getValues(arrLArray[Int],v:Int)返回数组中小于v,等于v,大于v的元素个数,要求三个值一起返回 2.数组反转,两两交换 */ object question09 { 
    def main(args: Array[String]): Unit = { 
    def getValues(arr: Array[Int], v: Int): (Int, Int, Int) = { 
    arr.foldLeft((0, 0, 0)) { 
    (x, y) => if (y > v) (x._1+1,x._2,x._3) else if (y == v) (x._1,x._2+1,x._3) else (x._1,x._2,x._3 + 1) } } val array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //2.数组反转,两两交换 val reverse: Array[Int] = array.reverse println(reverse.mkString("[",",","]")) val tuple: (Int, Int, Int) = getValues(array, 4) println(tuple) } } 

题目十:

讯享网//练习题目10 // 数据如下 :每个字母代表一个人, 统计任意一个人和其他人的共同好友 object question10 { 
    def main(args: Array[String]): Unit = { 
    val list: List[String] = List[String]( "A:B,C,D,F,E,O", "B:A,C,E,K", "C:F,A,D,I", "D:A,E,F,L", "E:B,C,D,M,L", "F:A,B,C,D,E,O,M", "G:A,C,D,E,F", "H:A,C,D,E,O", "I:A,O", "J:B,O", "K:A,C,D", "L:D,E,F", "M:E,F,G", "O:A,H,I,J" ) //先转换成 朋友->联系人 的形式 //然后打散,变成一个朋友->一个联系人的形式 //然后根据 朋友 分组,那拥有相同朋友的联系人都会在一个组 val friendsList: List[(String, String)] = list.flatMap { 
    str => val strings: Array[String] = str.split(":") val friends: Array[String] = strings(1).split(",") val tuples: ArrayBuffer[(String, String)] = ArrayBuffer[(String, String)]() for (friend <- friends) { 
    tuples.append((friend, strings(0))) } tuples }.groupBy(_._1) .mapValues { 
    list => val builder = new StringBuilder() builder.append(list.head._2) for (tuple <- list.tail) { 
    builder.append(",").append(tuple._2) } builder.toString() }.toList.sortBy(_._1) friendsList.foreach{ 
    case (t1,t2)=> println(s"$t1->$t2") } } } 

题目十一:

//SQL join object question11 { 
    def main(args: Array[String]): Unit = { 
    val order: File = new File("D:\\JetBrains\\IdeaProjects\\KGC_BigData\\k05_scala\\src\\main\\scala\\practice\\data\\order.txt") val user: File = new File("D:\\JetBrains\\IdeaProjects\\KGC_BigData\\k05_scala\\src\\main\\scala\\practice\\data\\user.txt") //读取数据 val orderSource: BufferedSource = Source.fromFile(order) val userSource: BufferedSource = Source.fromFile(user) val orderIter: Iterator[String] = orderSource.getLines() val userIter: Iterator[String] = userSource.getLines() //转换结构 val orderList: List[(String, String)] = orderIter.map { 
    str => val line: Array[String] = str.split(",") (line(1), str) }.toList val userList: List[(String, String)] = { 
    userIter.map { 
    str => val line: Array[String] = str.split(",") (line(0), str) } }.toList val joinMap: Map[String, ListBuffer[String]] = userList .union(orderList) .groupBy(_._1) .mapValues(_.map(_._2)) .map { 
    case (k, v) => val buffer: ListBuffer[String] = ListBuffer[String]() val list: List[String] = v.filter(_.length > 1) val userInfo: String = list.head val key: String = userInfo.replaceAll(",", "\t") list .tail //只有一个元素就是join失败 .foreach { 
    str => val filterStr: String = str.split(",").filter(_ != k).mkString("\t") buffer.append(filterStr) } (key, buffer) } joinMap.foreach { 
    case (k, v) => for (str <- v) { 
    println(k + "------>" + str) } } } } 

题目十二:

讯享网/* 练习题目12 数据如下: 统计线段在每个点重叠的次数 , 并按照从高到低排序输出 1,4 2,5 4,6 2,4 3,6 4,6 1,5 */ object question12 { 
    def main(args: Array[String]): Unit = { 
    //思路:终点和起点对接,就是端点重合 //将终点反转,分组聚合,求count //要过滤原数据后在求count val list: List[(Int,Int)] = List[(Int,Int)]( (1, 4), (2, 5),(4, 6),(2, 4),(3, 6), (4, 6),(1, 5) ) val list1: List[(Int, Int)] = list.map { 
    t => (t._2, t._1) } val resultMap: Map[Int, Int] = list .union(list1) .groupBy(_._1) .mapValues(_.diff(list).length) println(resultMap.mkString("\n")) } } 

题目十三:

/* 练习题目14 请统计网站PV UV */ object question13 { 
    def main(args: Array[String]): Unit = { 
    val log: File = new File("D:\\JetBrains\\IdeaProjects\\KGC_BigData\\k05_scala\\src\\main\\scala\\practice\\data\\weblog.txt") val logSource: BufferedSource = Source.fromFile(log) val logList: List[String] = logSource.getLines().toList println("UV:"+logList.length) val userList: List[String] = logList.map { 
    str => val strings: Array[String] = str .split(",") strings(1) }.filter(_.nonEmpty) .distinct println("PV:"+userList.length) } } 

题目十四:

讯享网/* 练习题目14 统计文本文件中单词出现的次数 wordcount */ object question14 { 
    def main(args: Array[String]): Unit = { 
    val wordFile: File = new File("D:\\JetBrains\\IdeaProjects\\KGC_BigData\\k05_scala\\src\\main\\scala\\practice\\data\\article.txt") val worldSource: BufferedSource = Source.fromFile(wordFile) val wordsList: List[String] = worldSource.getLines().toList val worldCount: List[(String, Int)] = wordsList.flatMap { 
    line => val words: Array[String] = line.split(" ") words.map((_, 1)) }.groupBy(_._1) .mapValues(_.length) .toList .sortBy(_._2).reverse .take(5) println(worldCount.mkString("\n")) } } 
小讯
上一篇 2025-02-11 23:23
下一篇 2025-02-15 13:49

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/67774.html