《快学Scala》, <Scala For the Impatient>习题第三章
2016-07-13 21:25
447 查看
1. Write a code snippet that sets a
to an array of n
random integers between 0
(inclusive) and n
(exclusive).
def genRandomArray(n: Int) : Array[Int] = for (i <- 0.until(n).toArray) yield scala.util.Random.nextInt(n - 1)
2. Write a loop that swaps adjacent elements of an array of integers. For example, Array(1, 2, 3, 4, 5)
becomes Array(2, 1, 4, 3, 5)
.
scala> :paste // Entering paste mode (ctrl-D to finish) def swapArrayInPlace(arr: Array[Int]): Unit = { var temp = 0; for (i <- 0.until(arr.length, 2)) { if (i < arr.length - 2) { temp = arr(i + 1) arr(i + 1) = arr(i) arr(i) = temp } } } // Exiting paste mode, now interpreting. swapArrayInPlace: (arr: Array[Int])Unit scala> val a = Array(1,2,3,4,5) a: Array[Int] = Array(1, 2, 3, 4, 5) scala> swapArrayInPlace(a) scala> a res71: Array[Int] = Array(2, 1, 4, 3, 5)
3. Repeat the preceding assignment, but produce a new array with swapped values. Use for/yield
.
scala> :paste // Entering paste mode (ctrl-D to finish) def swapArray(arr: Array[Int]) : Array[Int] = for (i <- arr.indices.toArray) yield { if (i == arr.length - 1) arr(i) else if (i % 2 == 0) arr(i+1) else arr(i-1) } // Exiting paste mode, now interpreting. swapArray: (arr: Array[Int])Array[Int] scala> swapArray(Array(1,2,3,4,5)) res60: Array[Int] = Array(2, 1, 4, 3, 5)
4. Given an array of integers, produce a new array that contains all positive values of the original array, in their original order, followed by all values that are zero or negative, in their original order.
def reorder(arr: Array[Int]) : Array[Int] = { arr.filter(_ > 0) ++ arr.filter(_ <= 0) } scala> reorder(Array(4,-1,0, 52,15,6,-7)) res72: Array[Int] = Array(4, 52, 15, 6, -1, 0, -7)
5. How do you compute the average of an Array[Double]
?
相关文章推荐
- Windows下Scala环境搭建
- Windows7下安装Scala 2.9.2教程
- Scala代码实现列出Hadoop 文件夹下面的所有文件
- ClassNotFoundException:scala.PreDef$
- sbt创建web项目
- XML 文件解析--含Unicode字符的XML文件
- Scala 学习随笔
- Scala 小程序记录(学习期间的代码片段)
- Spark机器学习(二) 局部向量 Local-- Data Types - MLlib
- Spark机器学习(三) Labeled point-- Data Types
- 分分钟掌握快速排序(Java / Scala 实现)
- Scala极速入门
- Spark初探
- Scala实现REST操作
- Scala method call syntax
- 关于Scala多重继承的菱形问题
- Scala 高阶函数(high-order function)剖析
- Scala Monad Design Pattern
- Scala类型系统——高级类类型(higher-kinded types)
- Spray.io搭建Rest服务