Skip to content

Instantly share code, notes, and snippets.

View carloscaldas's full-sized avatar

carloscaldas

View GitHub Profile
@carloscaldas
carloscaldas / scala-impatient-chapter3.scala
Last active September 26, 2016 23:07
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 }
@carloscaldas
carloscaldas / scala-impatient-chapter2.scala
Last active September 26, 2016 19:45
Scala for the Impatient 1st edition: Chapter 2 exercises solutions
//01. The signum of a number is 1 if the number is positive, –1 if it is negative, and 0 if it is zero. Write a function that computes this value.
scala> def signum(n : Int):Byte = if (n>0) 1 else if (n<0)-1 else 0
signum: (n: Int)Byte
//02. What is the value of an empty block expression {}? What is its type?
Unit