Assignment 6 (work in progress).
[Scala.git] / Assignment_05 / src / main / scala / Main.scala
1
2 object Main {
3 // Question 1: HOF on lists.
4 def lengthStrings(l: List[String]) = l map (_ length)
5 def dup[T](e: T, n: Int) = (1 to n) map (_ => e)
6 def dot(l1: List[Int], l2: List[Int]) = (l1 zip l2) map { case (a, b) => a * b }
7
8 // Question 2: Folding functions on lists.
9 def areTrue(l: List[Boolean]) = l reduceLeft (_ && _)
10 def lString(l: List[String]): Int = l.foldLeft(0)((acc, s) => acc + s.length())
11 def longest(l: List[String]): (Int, String) = l.foldLeft(0, ""){ case (curr@(len, longestStr), str) => if (str.length() > len) (str.length(), str) else curr }
12 def isPresent[T](l: List[T], e: T): Boolean = l.foldLeft(false)((acc, e2) => acc || e == e2)
13 def flattenList(l: List[Any]): List[Any] = l.foldRight (List.empty[Any]) {
14 case (e: List[Any], acc) => flattenList(e) ++ acc
15 case (e, acc) => e:: acc
16 }
17
18 // Question 3: Tuples.
19 def primeSum(max: Int): List[(Int, Int)] =
20 for {
21 i <- (1 to max).toList
22 j <- (1 to max).toList
23 if isPrime(i + j)
24 } yield (i, j)
25
26 def isPrime(i: Int): Boolean =
27 if (i <= 1 || i % 2 == 0)
28 false
29 else
30 !(3 to Math.sqrt(i).toInt).exists(i % _ == 0)
31
32 // a)
33 def primeSumUnique1(max: Int): List[(Int, Int)] = {
34 def loop(l: List[(Int, Int)]): List[(Int, Int)] = l match {
35 case Nil => Nil
36 case (t@(a, b)) :: rest => if (a > b) t :: loop(rest) else loop(rest)
37 }
38 loop(primeSum(max))
39 }
40
41 // b)
42 def primeSumUnique2(max: Int): List[(Int, Int)] =
43 primeSum(max).foldLeft(List[(Int, Int)]())((acc, t) => if (t._1 > t._2) t :: acc else acc)
44
45 // Question 4.
46 val cities = List("Paris", "London", "Berlin", "Lausanne")
47 val relatives = List("Grandma", "Grandpa", "Aunt Lottie", "Dad")
48 val travellers = List("Pierre-Andre", "Rachel")
49
50 def postcards : List[String] =
51 for {
52 city <- cities
53 relative <- relatives
54 traveller <- travellers
55 if relative.charAt(0).toLower == 'g'
56 } yield s"Dear ${relative}, Wish you were here in ${city}! Love, ${traveller}"
57
58 // Question 5.
59 def queens(n: Int): List[List[(Int, Int)]] = {
60 def placeQueens(k: Int): List[List[(Int, Int)]] =
61 if (k == 0)
62 List(List())
63 else
64 for {
65 queens <- placeQueens(k - 1)
66 column <- 1 to n
67 queen = (k, column)
68 if isSafe(queen, queens)
69 } yield queen :: queens
70 placeQueens(n)
71 }
72
73 def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) =
74 queens forall (q => !inCheck(queen, q))
75
76 def inCheck(q1: (Int, Int), q2: (Int, Int)) =
77 q1._1 == q2._1 || // Same row.
78 q1._2 == q2._2 || // Same column.
79 (q1._1 - q2._1).abs == (q1._2 - q2._2).abs // On diagonal.
80
81 def printChessBoard(boards: List[List[(Int, Int)]]) =
82 (boards zipWithIndex).foldLeft("") { case (acc, (board, index)) =>
83 acc + s"Solution ${index + 1}:\n" + {
84 val l = board.length
85 (for {r <- 1 to l; c <- 1 to l} yield (if (c == 1) "|" else "") + (if (board contains(r, c)) "\u265b" else "_") + "|" + (if (c == l) "\n" else "")) reduce (_ + _)
86 }
87 }
88
89 def main(args: Array[String]): Unit = {
90 println("Question 1")
91 println(s"a) ${lengthStrings(List("How", "long", "are", "we?"))}")
92 println(s"b) ${dup("foo", 5)}")
93 println(s"c) ${dot(List(1, 2, 3), List(2, 4, 3))}")
94
95 println("\nQuestion 2")
96 println("a)")
97 println(s"${areTrue(List(true, true, false))}")
98 println(s"${areTrue(List(true, true, true))}")
99 println("b)")
100 println(s"${lString(List("Folding", "is", "fun"))}")
101 println("c)")
102 println(s"${longest(List("What", "is", "the", "longest?"))}")
103 println("d)")
104 println(s"${isPresent(List(1, 2, 3, 4), 5)}")
105 println(s"${isPresent(List(1, 2, 3, 4), 3)}")
106 println("e)")
107 val l = List(List(1, 1), 2, List(3, List(5, 8)));
108 println(s"flattenList($l): ${flattenList(l)}")
109
110 println("\nQuestion 3")
111 println(s"a) ${primeSumUnique1(7)}")
112 println(s"b) ${primeSumUnique2(7)}")
113
114 println("\nQuestion 4")
115 postcards.foreach(p => println(p))
116
117 println("\nQuestion 5")
118 println(printChessBoard(queens(4)))
119 }
120 }