package ex13_01 import scala.collection.mutable.SortedSet import scala.collection.mutable.Map object Main extends App{ def indexes(s: String): Map[Char,SortedSet[Int]]={ val map = Map[Char,SortedSet[Int]]() for(i <- 0 until s.length()){ //map += s(i).toChar -> (map.getOrElse(s(i).toChar, SortedSet(i)) += i) map(s(i).toChar) = (map.getOrElse(s(i).toChar, SortedSet(i)) += i) } map } val map = indexes("Mississippi") println(map.mkString(",")) } /* output: M -> TreeSet(0),s -> TreeSet(2, 3, 5, 6),p -> TreeSet(8, 9),i -> TreeSet(1, 4, 7, 10) */
package ex13_02 object Main extends App { def indexes(s: String): Map[Char, List[Int]] = { var map = Map[Char, List[Int]]() for (i <- 0 until s.length()) { val templist = map.get(s(i).toChar) if (templist == None) map += s(i).toChar -> List(i) else if (!templist.contains(i)) map += s(i).toChar -> (templist.get ::: List(i)) } map } val map = indexes("Mississippi") println(map.mkString(",")) } /* output: M -> List(0),i -> List(1, 4, 7, 10),s -> List(2, 3, 5, 6),p -> List(8, 9) */
package ex13_03 import scala.collection.mutable.MutableList object Main extends App { def removeZero(lst: MutableList[Int]):MutableList[Int]={ val mylist = lst.filter( _ != 0) mylist } val a = MutableList(1,2,3,0,5,0,7) println(a) println(removeZero(a)) } /* output: MutableList(1, 2, 3, 0, 5, 0, 7) MutableList(1, 2, 3, 5, 7) */
package ex13_04 import scala.collection.mutable.MutableList object Main extends App { def getScores(arr: Array[String], map: Map[String, Int]): Array[Int] = { val scores = arr.flatMap(map.get(_)) scores } val arr = Array("Tom", "Fred", "Harry") val map = Map("Tom" -> 3, "Dick" -> 4, "Harry" -> 5) val scores = getScores(arr, map) println(scores.mkString(",")) } /* output: 3,5 */
package ex13_05 import scala.collection.mutable.MutableList object Main extends App { def mkString(arr: Array[String], left: String, mid: String, right: String): String = { val sb = new StringBuilder() sb.append(left) sb.append(arr.reduceLeft("%s%s%s".format(_, mid, _))) sb.append(right) sb.toString() } val arr = Array("Jonathan", "will", "become", "a", "billionaire", "in", "five", "years") println(mkString(arr, "-*-", " ", "-*-")) } /* output: -*-Jonathan will become a billionaire in five years-*- */
package ex13_06 import scala.collection.mutable.MutableList //def ::(x: A): List[A] //[user case] Adds an element at the beginning of this list. //def :+(elem: A): List[A] //[use case] A copy of the list with an element appended. object Main extends App { val lst = List(1,2,3,4,5,6,7) println(lst) val a = (lst :\ List[Int]())(_ :: _) // equivalent to (lst :\ List[Int]())(_ +: _) println(a) val b = (List[Int]() /: lst)(_ :+ _) println(b) //to reverse val c = (lst :\ List[Int]())( (e,r) => r :+ e ) println(c) val d = (List[Int]() /: lst)( (r,e) => e +: r ) println(d) } /* output: List(1, 2, 3, 4, 5, 6, 7) List(1, 2, 3, 4, 5, 6, 7) List(1, 2, 3, 4, 5, 6, 7) List(7, 6, 5, 4, 3, 2, 1) List(7, 6, 5, 4, 3, 2, 1) */
package ex13_07 import scala.collection.mutable.MutableList object Main extends App { val prices = List(5.0, 20.0, 9.95) val quantities = List(10, 2, 1) println((prices zip quantities) map { pair => pair._1 * pair._2 }) println((prices zip quantities) map { Function.tupled(_ * _) }) } /* output: List(50.0, 40.0, 9.95) List(50.0, 40.0, 9.95) */
package ex13_08 import scala.collection.mutable.MutableList object Main extends App { def to2DArray(arr: Array[Int], cols: Int): Array[Array[Int]] = { var result = Array[Array[Int]]() for (i <- arr.grouped(3)) result = result :+ i result } val arr = Array(1, 2, 3, 4, 5, 6) val result = to2DArray(arr, 3) result.foreach(it => println(it.mkString("[", ",", "]"))) } /* output: [1,2,3] [4,5,6] */
9. Harry Hacker写了一个从命令行接受一系列文件名的程序。对每个文件名,他都启动一个新的线程来读取文件内容并更新一个字母出现频率映射,声明为:
val frequencies = new scala.collection.multable.HashMap[Char,Int] with scala.collection.mutable.SynchronizedMap[Char,Int]
当读到字母c时,他调用
frequencies(c) = frequencies.getOrElse(c,0) + 1
为什么这样做得不到正确答案?如果他用如下方式实现呢:
回答: 并发问题,并发修改集合不安全.修改后的代码和修改前的代码没有什么太大的区别.
10. Harry Hacker把文件读取到字符串中,然后想对字符串的不同部分用并行集合来并发地更新字母出现频率映射。他用了如下代码:
val frequencies = new scala.collection.mutable.HashMap[Char,Int] for(c <- str.par) frequencies(c) = frequencies.getOrElse(c,0) + 1
package ex13_10_a import scala.collection.immutable.HashMap //import scala.collection.mutable.HashMap //type mismatch; found : scala.collection.mutable.Map[Char,Int] required: scala.collection.mutable.HashMap[Char,Int] //type mismatch; found : scala.collection.mutable.Map[Char,Int] required: scala.collection.mutable.HashMap[Char,Int] //Implicit conversion found: c ⇒ ArrowAssoc(c): ArrowAssoc[Char] object Main extends App { def frequence(str: String): HashMap[Char, Int] = { val result = str.par.aggregate(HashMap[Char, Int]())( { (m, c) => m + ( c -> (m.getOrElse(c,0) + 1) ) }, { (m1, m2) => (m1.keySet ++ m2.keySet).foldLeft( HashMap[Char, Int]() ) { (result, k) => result + (k -> (m1.getOrElse(k, 0) + m2.getOrElse(k, 0))) } }) result } //val str = "You were asking me that how deep I've been loving you." val str = "Hello" println(frequence(str)) } /* output: Map(e -> 1, l -> 2, H -> 1, o -> 1) */