Exercise Solutions

1.
  • def wordsInName(name:String):Int
  • def lastNameFirst(name:String):String
  • def makeTLA(word1:String, word2:String, word3:String):String
  • def numInUnitCircle(p1:(Double,Double), p2:(Double,Double), p3:(Double,Double), p4:(Double,Double), p5:(Double,Double), p6:(Double,Double), p7:(Double,Double), p8:(Double,Double), p9:(Double,Double), p10:(Double,Double)):Int
  • def numPrimeFactors(n:Int):Int
  • def numPositiveFactors(n:Int):Int
  • def fahrenheitToCelsius(f:Double):Double
  • def fahrenheitToCelsiusAndKelvin(f:Double):(Double,Double)

2.
def canDrink(age:Int):Boolean = age>=21
def canRide(height:Int):Boolean = height>=48 && height<74

3.
def isPalindrome(str:String):Boolean = str == str.reverse

4.
def combineARGB(alpha:Int, red:Int, green:Int, blue:Int):Int = {
  (alpha << 24) | (red << 16) | (green << 8) | blue
}


5.
def combineARGB(alpha:Double, red:Double, green:Double, blue:Double):Int = {
  ((alpha
*256).toInt << 24) | ((red*256).toInt << 16) | ((green*256).toInt << 8) | (blue*256).toInt
}

6.
def splitARGB(argb:Int):(Int,Int,Int,Int) = {
  val alpha = (argb >>> 24)
  val red = (argb >>> 16) & 0xFF
  val green = (argb >>> 8) & 0xFF
  val blue = argb & 0xFF
  (alpha,red,green,blue)
}

7.
def splitARGB(argb:Int):(Double,Double,Double,Double) = {
  val alpha = (argb >>> 24)/256.0
  val red = ((argb >>> 16) & 0xFF)/256.0
  val green = ((argb >>> 8) & 0xFF)/256.0
  val blue = (argb & 0xFF)/256.0

  (alpha,red,green,blue)
}

8.
def isInUnitCircle(x:Double,y:Double):Boolean = {
 
val magSqr = x*x+y*y
  magSqr<=1.0
}

9.
def fahrenheitToCelsius(degreesF:Double):Double = {
  (degreesF-32)/1.8
}

10.
def milesTokm(miles:Double):Double = miles * 1.60934

11.
def secondsToYears(secs:Double):Double = secs/(365*24*60*60)

12.
def auToMiles(au:Double):Double = au * 92.956e6

13.
def smallestOfFour(a:Int,b:Int,c:Int,d:Int):Int = a min b min c min d
def smallestOfFour(a:Int,b:Int,c:Int,d:Int):Int = {
  var min = a
  if(b<min) min = b
  if(c<min) min = c
  if(d<min) min = d
  min
}

14.
def median(a:Int,b:Int,c:Int):Int = {
  if(a<=b) {
    if(a>=c) a
    else if(b<=c) b else c
  } else {
    if(b>=c) b
    else if(a<=c) a else c
  }
}

// This is a more interesting solution. See if you can figure out why it works.
def median(a:Int,b:Int,c:Int):Int = {
  val smallest = a min b min c
  val largest = a max b max c
  a+b+c-smallest-largest
}
Comments