Scala

Learning Scala

Scala for the intrigued (article)

Twitter’s effective guide to Scala

Scala for the impatient (Free ebook)

Programming scala (free online edition)

My answers :

3. Arrays

3.1.Write a code snippet that sets a to an array of n random integers between 0 (inclusive) and n (exclusive)

val a = 1 to 15 filter { _ > 0 } map { Random.nextInt(_) } // example with 15

3.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).

val a = Array(2,3,5,7,11,18) for (i<-0 until a.length) { if (i%2==0) println(a(i+1) else println(a(i-1)) }

3.3.Repeat the preceding assignment, but produce a new array with the swapped values. Use for/yield

for (i<-0 until a.length) yield (if (i%2==0) a(i+1) else a(i-1))

3.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

import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int](3,2,-5,7,-15,18,-1);
val c = ArrayBuffer[Int]()
val d = ArrayBuffer[Int]()
for (elem<-b) {
if (elem>=0) {
d+=elem
} else {
c+=elem
}
}
d++=c.toArray

3.5.How do you compute the average of an Array[Double]?

Array[Double].sum()/Array[Double].size()

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

reverse

3.7.Write a code snippet that produces all values from an array with duplicates removed

val b = Array[Int](3,2,-5,7,7,-15,18,-18); b.distinct

3.9Make a collection of all time zones returned by java.util.TimeZone.getAvailableIDs that are in America. Strip off the “America/” prefix and sort the result.

import java.util.TimeZone.getAvailableIDsScala val arr =  getAvailableIDs() for (elem<-arr if (elem.contains(“America”))) yield elem

4.1.Set up a map of prices for a number of gizmos that you covet. Then produce a second map with the same keys and the prices at a 10 percent discount

val wishList= Map(“iphone”->499, “ipad”->699, “imac”->1499) for ((k, v) <- wishList) yield (v*0.9)

4.2.Write a program that reads words from a file. Use a mutable map to count how often each word appears.

val in = new java.util.Scanner(new java.io.File(“D:\\tmp\\scal.txt”)); var a=scala.collection.mutable.Map[String, Int](); while (in.hasNext()) { val v = in.next() var count = a.getOrElse(v, 0) count+=1 println(“->”+v+” “+count) a = a + (v->count) }

4.3.Repeat the preceding exercise with an immutable map

var a=Map[String, Int]();

4.4.Repeat the preceding exercise with a sorted map, so that the words are printed in sorted order

var a= scala.collection.immutable.SortedMap[String, Int]()

4.5.Repeat the preceding exercise with a java.util.TreeMap that you adapt to the Scala API.

import scala.collection.JavaConversions.mapAsScalaMap
val in = new java.util.Scanner(new java.io.File(“D:\\tmp\\scal.txt”))
var a: scala.collection.mutable.Map[String, Int] = new java.util.TreeMap[String, Int]
while (in.hasNext()) {
val v = in.next()
var count = a.getOrElse(v, 0)
count+=1
println(“->”+v+” “+count)
a = a + (v->count)
}

4.6 Define a linked hash map that maps “Monday” to java.util.Calendar.MONDAY, and
similarly for the other weekdays

import java.util.Calendar
val daysLinkedMap = new scala.collection.mutable.LinkedHashMap[String, Int]
daysLinkedMap += (“Monday” -> Calendar.MONDAY)
daysLinkedMap += (“Thuesday” -> Calendar.THUESDAY)
daysLinkedMap += (“Wednesday” -> Calendar.WEDNESDAY)
daysLinkedMap += (“Thursday” -> Calendar.THURSDAY)
daysLinkedMap += (“Friday” -> Calendar.FRIDAY)
daysLinkedMap += (“Saturday” -> Calendar.SATURDAY)
daysLinkedMap += (“Sunday” -> Calendar.SUNDAY)

4.7 Print a table of all Java properties

import scala.collection.JavaConversions.propertiesAsScalaMap
var lengthMax:Int=0;
for (k <- props.keySet )   if (k.length > lengthMax) lengthMax = k.length
for ((k,v) <- props) { Console.print(k);Console.print(” “*(lengthMax-k.length));Console.print(“| “+v )}

4.8 Write a function minmax(values: Array[Int]) that returns a pair containing the
smallest and largest values in the array

def minmax(values: Array[Int]):(Int,Int) = {
var min:Int=0;
var max:Int=0;
for ( v <- values) {
if (v > max) {
max = v;
}
else if (v < min) {
min = v;
}
}
(min, max)
}

4.9 Write a function lteqgt(values: Array[Int], v: Int) that returns a triple containing
the counts of values less than v, equal to v, and greater than v.

def lteqgt(values: Array[Int], p: Int):(Int,Int, Int) = {
var eq:Int=0;
var lt:Int=0;
var gt:Int=0;
for ( v <- values) {
if (v > p) {
gt += 1;
}
else if (v==p) {
eq += 1;
}
else if (v < p) {
lt += 1;
}
}
(lt, eq, gt)
}

4.10 “Hello”.zip(“World”) associates (H,W), (e,o), (l,r), (l,l), (o,d) which is not what’s expected.

5.2 Write a class BankAccount with methods deposit and withdraw, and a read-only
property balance.

class BankAccount {
var bal=0

def deposit(amount:Int) {bal += amount}
def balance = bal
}

5.3Write a class Time with read-only properties hours and minutes and a method
before(other: Time): Boolean that checks whether this time comes before the
other. A Time object should be constructed as new Time(hrs, min), where hrs is in
military time format (between 0 and 23).

class Time {

var h = 0
var m = 0

def hours = h
def minutes = m

def this(hrs:Int, min:Int) {
this()
this.h = hrs
this.m = min
}

def before(other:Time): Boolean = {

if (this.h < other.h)
true
else if ( this.h > other.h)
false
else if ( this.m < other.m)
true
else
false
}
}

4.4Reimplement the Time class from the preceding exercise so that the internal
representation is the number of minutes since midnight (between 0 and
24 × 60 – 1). Do not change the public interface. That is, client code should be
unaffected by your change.

this.h = hrs*60-1

4.5 Make a class Student with read-write JavaBeans properties name (of type String)
and id (of type Long). What methods are generated? (Use javap to check.)

import scala.reflect.BeanProperty
class Person {
@BeanProperty var name: String = _
@BeanProperty var id:Long = _
}

D:\tmp>javap Person
Compiled from “Person.scala”
public class Person extends java.lang.Object implements scala.ScalaObject{
public java.lang.String name();
public void name_$eq(java.lang.String);
public void setName(java.lang.String);
public long id();
public void id_$eq(long);
public void setId(long);
public long getId();
public java.lang.String getName();
public Person();
}

Scala schools

 

 

Advertisements
  1. Hans
    November 29, 2012 at 11:17 am

    Hello,

    In your solution for Ex 3.3: you may be running against an ArrayIndexOutOfBoundsException for an odd number of items in the array.
    I used an extra guard clause:

    
    for (i <- 0 until a.length) yield (
        if (i % 2 == 1)
          a(i - 1)
        else
        if (i + 1 < a.length) a(i + 1) else a(i))
    
    

    Thank you for posting your solutions.

    HTH,

    Hans

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: