Scala 小代码练习
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