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)
elseif (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.