|
1 |
|
2 // Task 1 |
|
3 |
|
4 2 + 2 |
|
5 1 / 2 |
|
6 1.0 / 2 |
|
7 1 / 2.0 |
|
8 1 / 0 |
|
9 1.0 / 0.0 |
|
10 true == false |
|
11 true && false |
|
12 1 > 1.0 |
|
13 "12345".length |
|
14 List(1,2,1).size |
|
15 Set(1,2,1).size |
|
16 List(1) == List(1) |
|
17 Set(1,2,3) == Set(3,2,1) |
|
18 Array(1) == Array(1) |
|
19 Array(1).sameElements(Array(1)) |
|
20 |
|
21 |
|
22 // Task 2 |
|
23 |
|
24 val z = 42 |
|
25 z = z + 1 . // error |
|
26 val x = 2 * z |
|
27 val z = 466 // old z not accessible anymore |
|
28 println(x) |
|
29 |
|
30 |
|
31 // Task 3 |
|
32 println("Hello " ++ "World") |
|
33 List(1,2,3,4).mkString("\n") |
|
34 List(1,2,3,4).mkString("(", "|", ")") |
|
35 |
|
36 |
|
37 // Task 4 |
|
38 def miles2meters(m: Int): Int = m * 1609 |
|
39 |
|
40 |
|
41 // Task 5 |
|
42 |
|
43 val s1 = "foo" |
|
44 val s2 = "bar" |
|
45 val s3 = "foobar" |
|
46 if (s1 == s2) print("equal") else print("unequal") |
|
47 if (s1 ++ s2 == s3) print("equal") else print("unequal") |
|
48 |
|
49 |
|
50 // Task 6 |
|
51 for (x <- (1 to 5).toList; |
|
52 y <- (1 to 5).toList; |
|
53 z <- (1 to 5).toList) yield (x,y,z) |
|
54 |
|
55 for (x <- (1 to 5).toList; |
|
56 y <- (1 to 5).toList; |
|
57 z <- (1 to 5).toList; |
|
58 if (x + y + z) % 3 == 0) yield (x,y,z) |
|
59 |
|
60 (for (x <- (1 to 5).toList; |
|
61 y <- (1 to 5).toList; |
|
62 z <- (1 to 5).toList; |
|
63 if (x + y + z) % 3 == 0) yield (x,y,z)).sortBy(_._2) |
|
64 |
|
65 |
|
66 |
|
67 // Task 7 |
|
68 |
|
69 // first version with using an accumulator |
|
70 |
|
71 def cnt(xs: List[Int], acc: List[(Int, Int)] = Nil) : List[(Int, Int)] = |
|
72 (xs, acc) match { |
|
73 case (Nil, acc) => acc.reverse |
|
74 case (x::xs, Nil) => cnt(xs, (x, 1)::Nil) |
|
75 case (x::xs, (y, n)::ys) => |
|
76 if (x == y) cnt(xs, (y, n + 1)::ys) |
|
77 else cnt(xs, (x, 1)::(y, n)::ys) |
|
78 } |
|
79 |
|
80 def toStr(p: (Int, Int)) = |
|
81 if (p._2 == 1) s"${p._1}" else s"${p._2} x ${p._1}" |
|
82 |
|
83 def pp_list(xs: List[Int]) = { |
|
84 cnt(xs).map(toStr) |
|
85 } |
|
86 |
|
87 pp_list(List(1,1,1,2,3,3)) // List(3 x 1, 2, 2 x 3) |
|
88 pp_list(List(1,2,3,4,4,4)) // List(1, 2, 3, 3 x 4) |
|
89 pp_list(List(1,1,1,1,1,1)) // List(6 x 1) |
|
90 pp_list(List(1,1,1,2,1,1)) // List(3 x 1, 2, 2 x 1) |
|
91 |
|
92 // second version with just a simple counter |
|
93 |
|
94 def cnt2(xs: List[Int], n : Int = 0) : List[(Int, Int)] = xs match { |
|
95 case Nil => Nil |
|
96 case x::Nil => (x, n + 1)::Nil |
|
97 case x::y::tail => |
|
98 if (x == y) cnt2(y::tail, n + 1) |
|
99 else (x, n + 1)::cnt2(y::tail, 0) |
|
100 } |
|
101 |
|
102 def pp_list2(xs: List[Int]) = { |
|
103 cnt2(xs).map(toStr) |
|
104 } |
|
105 |
|
106 pp_list2(List(1,1,1,2,3,3)) // List(3 x 1, 2, 2 x 3) |
|
107 pp_list2(List(1,2,3,4,4,4)) // List(1, 2, 3, 3 x 4) |
|
108 pp_list2(List(1,1,1,1,1,1)) // List(6 x 1) |
|
109 pp_list2(List(1,1,1,2,1,1)) // List(3 x 1, 2, 2 x 1) |