Scala小代码<持续更新>

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





















转载于:https://my.oschina.net/jinfu/blog/478820

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值