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
}
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
18 // Question 3: Tuples.
19 def primeSum(max
: Int
): List
[(Int
, Int
)] =
21 i
<- (1 to max
).toList
22 j
<- (1 to max
).toList
26 def isPrime(i
: Int
): Boolean
=
27 if (i
<= 1 || i
% 2 == 0)
30 !(3 to Math
.sqrt(i
).toInt
).exists(i
% _
== 0)
33 def primeSumUnique1(max
: Int
): List
[(Int
, Int
)] = {
34 def loop(l
: List
[(Int
, Int
)]): List
[(Int
, Int
)] = l
match {
36 case (t@
(a
, b
)) :: rest
=> if (a
> b
) t
:: loop(rest
) else loop(rest
)
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
)
46 val cities
= List("Paris", "London", "Berlin", "Lausanne")
47 val relatives
= List("Grandma", "Grandpa", "Aunt Lottie", "Dad")
48 val travellers
= List("Pierre-Andre", "Rachel")
50 def postcards
: List
[String
] =
54 traveller
<- travellers
55 if relative
.charAt(0).toLower
== 'g'
56 } yield s
"Dear ${relative}, Wish you were here in ${city}! Love, ${traveller}"
59 def queens(n
: Int
): List
[List
[(Int
, Int
)]] = {
60 def placeQueens(k
: Int
): List
[List
[(Int
, Int
)]] =
65 queens
<- placeQueens(k
- 1)
68 if isSafe(queen
, queens
)
69 } yield queen
:: queens
73 def isSafe(queen
: (Int
, Int
), queens
: List
[(Int
, Int
)]) =
74 queens
forall (q
=> !inCheck(queen
, q
))
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.
81 def printChessBoard(boards
: List
[List
[(Int
, Int
)]]) =
82 (boards zipWithIndex
).foldLeft("") { case (acc
, (board
, index
)) =>
83 acc
+ s
"Solution ${index + 1}:\n" + {
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 (_
+ _
)
89 def main(args
: Array
[String
]): Unit
= {
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))}")
95 println("\nQuestion 2")
97 println(s
"${areTrue(List(true, true, false))}")
98 println(s
"${areTrue(List(true, true, true))}")
100 println(s
"${lString(List("Folding
", "is
", "fun
"))}")
102 println(s
"${longest(List("What
", "is
", "the
", "longest?
"))}")
104 println(s
"${isPresent(List(1, 2, 3, 4), 5)}")
105 println(s
"${isPresent(List(1, 2, 3, 4), 3)}")
107 val l
= List(List(1, 1), 2, List(3, List(5, 8)));
108 println(s
"flattenList($l): ${flattenList(l)}")
110 println("\nQuestion 3")
111 println(s
"a) ${primeSumUnique1(7)}")
112 println(s
"b) ${primeSumUnique2(7)}")
114 println("\nQuestion 4")
115 postcards
.foreach(p
=> println(p
))
117 println("\nQuestion 5")
118 println(printChessBoard(queens(4)))