Scala小代码<持续更新>
2015-07-15 14:22
288 查看
Scala 小代码练习
1.List 集合去重
2. FlatMap
3.复制集合元素
4. 随机抽取
5.寻找字符串中第一个出现的字母
6.判断一个数字是否质数
7.计算两个正整数的最大公约数
8.MD5生成工具类
1.List 集合去重
Q: //示例与得到结果<以下如同> scala> List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e) res0: List[Symbol] = List('a, 'b, 'c, 'a, 'd, 'e) A : //scala 解析代码 val s = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e) s.foldRight(List[Symbol]()){(h,r)=> | if(r.isEmpty || r.head !=h) h :: r | else r | } res4: List[Symbol] = List('a, 'b, 'c, 'a, 'd, 'e) //完全去重(有缺陷)--返回值结果不是Symbo类型 scala> s.groupBy(_.toString).map(_._1) res5: scala.collection.immutable.Iterable[String] = List('e, 'a, 'b, 'c, 'd)
2. FlatMap
Q: scala>val s= List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e)) res0: List[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e) A: scala> s.flatMap{e=>List.make(e._1,e._2)} res19: List[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
3.复制集合元素
val t = List('a, 'b, 'c, 'c, 'd) scala> t.flatMap{List.fill(2)(_)} // 2表示复制的个数 res22: List[Symbol] = List('a, 'a, 'b, 'b, 'c, 'c, 'c, 'c, 'd, 'd)
4. 随机抽取
import scala.util.Random val s = 1 to 10 val ran = Random.shuffle(s).take(3) res : scala.collection.immutable.IndexedSeq[Int] = Vector(3, 8, 4)
5.寻找字符串中第一个出现的字母
val s = "abaccddeeff" def findNonRepeat(s:String):String = if(s.count(_ == s.head) > 1) findNonRepeat(s.tail.filterNot(_ == s.head)) else String valueOf (s.headOption. getOrElse("No Repeated")) res:findNonRepeat(s) ="b"
6.判断一个数字是否质数
def isPrime(i:Int):Boolean = if(i <=1) true else if (i == 2) false else !( 2 to (i-1)).exists(x=>(i % x ==0)) res:isPrime(7) =>true
7.计算两个正整数的最大公约数
*采用欧几里德算法实现* def gcd(m:Int,n:Int):Int = if(n == 0) m else gcd(n,m%n) res:gcd(36,63) =>9
8.MD5生成工具类
import java.security.MessageDigest object HashUtil { /** * Calculate an MD5 has of a string. Used to hashing a file name * * @param String * @return MD5 hash of specified string */ def md5(s:String): String = { val md5 = MessageDigest.getInstance("MD5") md5.reset() md5.update(s.getBytes()) md5.digest().map(0xFF & _).map { "%02x".format(_) }.foldLeft("") { _ + _ } } } res:HashUtil.md5("jinfu")=26a0fc979de541e8614aa54045c52585
相关文章推荐
- HDU-1094-A+B for Input-Output Practice (VI)(这个和上上题有区别?)
- java 静态块、非静态块、静态函数、构造函数 执行顺序
- java中各种路径。
- Java基础阶段总结
- 代码中定义布局
- python 使用multiprocessing需要注意的问题
- BC#42第一题
- JDK配置
- struts2中constant参数设置
- Java集合系列之TreeMap源码分析
- html在套成.aspx页面后 在ie6下变形错位的问题!
- eclipse导入工程出现 Unbound classpath variable Error
- HDU-1093-A+B for Input-Output Practice (V)(水题也WA?)
- 关于Raspbian中KODI无法播放视频的问题
- Spring如何处理线程并发
- java中Map集合的理解
- C/C++中宏定义的经典运用
- Win10升级10166版出现错误代码0X80310052怎么办?附解决方法
- java过滤特殊字符串
- eclipse DDMS功能无法使用