Skip to content

Instantly share code, notes, and snippets.

@carloscaldas
Last active September 26, 2016 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carloscaldas/3361321306faf82e76c967559b5cea33 to your computer and use it in GitHub Desktop.
Save carloscaldas/3361321306faf82e76c967559b5cea33 to your computer and use it in GitHub Desktop.
Scala for the Impactient 1st edition: Chapter 3 exercises solutions
//1. Write a code snippet that sets a to an array of n random integers between 0 (inclusive) and n (exclusive).
val n = 10
val arr = new Array[Int](n)
for (i <- 1 until n) arr(i) = scala.util.Random.nextInt(n)
//02. 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).
for (i <- 0 until arr.length-1 by 2) { val tmp = arr(i); arr(i) = arr(i+1); arr(i+1) = tmp }
//03. Repeat the preceding assignment, but produce a new array with the swapped values. Use for/yield
scala> (for (i<-0 to arr.length-2 by 2) yield Array(arr(i+1), arr(i))).flatten.toArray
res2: Array[Int] = Array(2, 1, 4, 3)
//04. 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
scala> val pair = arr.partition(x => x > 0)
pair: (Array[Int], Array[Int]) = (Array(4, 5, 8),Array(-5, -2, 0, -7))
scala> pair._1 ++ pair._2
res3: Array[Int] = Array(4, 5, 8, -5, -2, 0, -7)
//05. How do you compute the average of an Array[Double]?
scala> val arrd = Array(3.0, 6.0, 9.0)
arrd: Array[Double] = Array(3.0, 6.0, 9.0)
scala> arrd.sum / arr.length
res6: Double = 2.5714285714285716
//06. How do you rearrange the elements of an Array[Int] so that they appear in reverse sorted order? How do you do the same with an ArrayBuffer[Int]?
arr.reverse
//07. Write a code snippet that produces all values from an array with duplicates removed. (Hint: Look at Scaladoc.)
arr.distinct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment