您的位置:首页 > 其它

《快学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]
?

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  scala