P14 (*) -P15 (**)Duplicate the elements of a list,Duplicate the elements of a list a given number of
来源:互联网 发布:c语言表达式的值 编辑:程序博客网 时间:2024/06/05 18:14
scala> duplicate(List('a, 'b, 'c, 'c, 'd))res0: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd)
scala> duplicateN(3, List('a, 'b, 'c, 'c, 'd))res0: List[Symbol] = List('a, 'a, 'a, 'b, 'b, 'b, 'c, 'c, 'c, 'c, 'c, 'c, 'd, 'd, 'd)//14def duplicate[A](ls:List[A]):List[A]={ var list:List[A]=Nil ls.foreach(e=> for(i<-0 to 1){list=list:::List(e)} ) list}//15def duplicateN[A](N:Int,ls:List[A]):List[A]={ var list:List[A]=Nil ls.foreach(e=> for(i<-0 to N-1){list=list:::List(e)} ) list}def main(args: Array[String])= { println(duplicate(List('a,'b,'c,'c,'d))) println(duplicateN(4,List('a,'b,'c,'c,'d)))参考答案
def duplicate[A](ls: List[A]): List[A] = ls flatMap { e => List(e, e) }巧妙地使用flatmap的接受处理列表的函数并把结果连接起来 的作用。def duplicateN[A](n: Int, ls: List[A]): List[A] = ls flatMap { List.make(n, _) }make函数已经不支持了,没有找到直接替代的函数
0 0
- P14 (*) -P15 (**)Duplicate the elements of a list,Duplicate the elements of a list a given number of
- P14 (*) Duplicate the elements of a list.
- P15 (**) Replicate the elements of a list a given number of times.
- P23 (**) Extract a given number of randomly selected elements from a list.
- P25 (*) Generate a random permutation of the elements of a list.
- P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.
- MACRO of a method of loop list for visit elements
- The best way to get unique elements of a list in Python
- Given a non-empty array of integers, return the k most frequent elements.
- Getting the indexes of duplicate elements in arrays (Ruby)
- P27 (**) Group the elements of a set into disjoint subsets.
- Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or
- Elements of a Good Proposal
- Write a method that counts the number of occurrences of a given character in a string
- A list of the Oracle event codes
- P17 (*) Split a list into two parts; the length of the first part is given.
- [CrackCode] 4.4 Creates a linked list of all the nodes at each depth of a given tree
- A. The number of positions
- shell 脚本入门基础知识
- 我的进阶曲线之八
- Bundle作用及使用方法
- 使用 xcodebuild 从 archive 导出 ipa
- PHP 5时区
- P14 (*) -P15 (**)Duplicate the elements of a list,Duplicate the elements of a list a given number of
- python string 使用正则表达式 split()
- configure: error: Cannot locate header file libintl.h 错误的解决方法
- VC++中调用EXCEL方法
- [LeetCode][1]Two Sum
- 双目视觉学习总结(1)——相机标定
- Camera
- 升级到IOS9以后,QQ授权登录和QQ分享出现问题,不能正常使用了(二)
- MapReduce 工作原理图