《快學Scala》, 習題第三章

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]?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章