wsheets/wsh01.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Mon, 14 Nov 2022 12:04:21 +0000
changeset 444 7a0735db4788
child 447 f51e593903ac
permissions -rw-r--r--
updated


// Task 1

2 + 2
1 / 2
1.0 / 2
1 / 2.0
1 / 0
1.0 / 0.0
true == false
true && false
1 > 1.0
"12345".length
List(1,2,1).size
Set(1,2,1).size
List(1) == List(1)
Set(1,2,3) == Set(3,2,1)
Array(1) == Array(1)
Array(1).sameElements(Array(1))


// Task 2

val z = 42
z = z + 1 .       // error
val x = 2 * z
val z = 466       // old z not accessible anymore
println(x)


// Task 3
println("Hello " ++ "World")
List(1,2,3,4).mkString("\n")
List(1,2,3,4).mkString("(", "|", ")")


// Task 4
def miles2meters(m: Int): Int = m * 1609


// Task 5

val s1 = "foo"
val s2 = "bar"
val s3 = "foobar"
if (s1 == s2) print("equal") else print("unequal")
if (s1 ++ s2 == s3) print("equal") else print("unequal")


// Task 6
for (x <- (1 to 5).toList;
     y <- (1 to 5).toList;
     z <- (1 to 5).toList) yield (x,y,z)

for (x <- (1 to 5).toList;
     y <- (1 to 5).toList;
     z <- (1 to 5).toList;
     if (x + y + z) % 3 == 0) yield (x,y,z)

(for (x <- (1 to 5).toList;
     y <- (1 to 5).toList;
     z <- (1 to 5).toList;
     if (x + y + z) % 3 == 0) yield (x,y,z)).sortBy(_._2)



// Task 7

// first version with using an accumulator

def cnt(xs: List[Int], acc: List[(Int, Int)] = Nil) : List[(Int, Int)] = 
  (xs, acc) match { 
    case (Nil, acc) => acc.reverse
    case (x::xs, Nil) => cnt(xs, (x, 1)::Nil)
    case (x::xs, (y, n)::ys) =>  
        if (x == y) cnt(xs, (y, n + 1)::ys)
        else cnt(xs, (x, 1)::(y, n)::ys)
  }

def toStr(p: (Int, Int)) = 
    if (p._2 == 1) s"${p._1}" else s"${p._2} x ${p._1}"

def pp_list(xs: List[Int]) = {
   cnt(xs).map(toStr) 
}

pp_list(List(1,1,1,2,3,3))    //   List(3 x 1, 2, 2 x 3)
pp_list(List(1,2,3,4,4,4))    //   List(1, 2, 3, 3 x 4)
pp_list(List(1,1,1,1,1,1))    //   List(6 x 1)
pp_list(List(1,1,1,2,1,1))    //   List(3 x 1, 2, 2 x 1)

// second version with just a simple counter

def cnt2(xs: List[Int], n : Int = 0) : List[(Int, Int)] = xs match {
  case Nil => Nil
  case x::Nil => (x, n + 1)::Nil
  case x::y::tail => 
    if (x == y) cnt2(y::tail, n + 1) 
    else (x, n + 1)::cnt2(y::tail, 0)   
}

def pp_list2(xs: List[Int]) = {
   cnt2(xs).map(toStr) 
}

pp_list2(List(1,1,1,2,3,3))    //   List(3 x 1, 2, 2 x 3)
pp_list2(List(1,2,3,4,4,4))    //   List(1, 2, 3, 3 x 4)
pp_list2(List(1,1,1,1,1,1))    //   List(6 x 1)
pp_list2(List(1,1,1,2,1,1))    //   List(3 x 1, 2, 2 x 1)