Compare commits

...

5 Commits

Author SHA1 Message Date
056305fd72
added assignment 6 ex 4 2025-04-08 15:52:54 +02:00
f4e417571a
added assignment 6 ex 3 2025-04-08 15:35:05 +02:00
4eba7f3587
added assignment 6 ex 2 2025-04-08 15:29:08 +02:00
76a4f50075
added assignment 6 ex 1 2025-04-08 15:03:00 +02:00
41c0b80d8b
added lesson 6 2025-04-08 14:53:36 +02:00
10 changed files with 248 additions and 0 deletions

View File

@ -57,6 +57,13 @@
[Files](src/Lesson5)
- Lists
- High order functions
-
### Lesson 6 - Tuples and comprehensions
[Files](src/Lesson6)
- Tuples
- For-comprehension
- Yield
- Flatmap
### Midterm preparation
[Files](src/MidTermPrep1)

17
src/Assignment6/Ex1.sc Normal file
View File

@ -0,0 +1,17 @@
def flattenList(list: List[Any]): List[Any] = {
list.foldRight(List.empty[Any])(
(e, acc) => {
e match {
case l: List[Any] => flattenList(l) concat acc
case _ => e::acc
}
}
)
}
assert(
flattenList(
List(List(1,1), 2, List(3, List(5, 8)))
) == List(1,1,2,3,5,8)
)

38
src/Assignment6/Ex2.sc Normal file
View File

@ -0,0 +1,38 @@
def isPrime(i: Int): Boolean =
i match {
case i if i <= 1 => false
case 2 => true
case _ => !(2 to (i - 1)).exists(x => i % x == 0)
}
def primeSum(max: Int): List[(Int, Int)] =
for {
i <- (1 to max).toList
j <- (1 to max).toList
if (isPrime(i + j))
} yield (i, j)
def uniquePermutations(permutations: List[(Int, Int)]): List[(Int, Int)] = {
permutations match {
case Nil => Nil
case (a, b)::rest if rest contains(b, a) => uniquePermutations(rest)
case head::rest => head::uniquePermutations(rest)
}
}
def uniquePermutations2(permutations: List[(Int, Int)]): List[(Int, Int)] = {
permutations.foldRight(List.empty[(Int, Int)])(
(e, acc) => {
e match {
case (a, b) if acc contains (b, a) => acc
case _ => e::acc
}
}
)
}
val perms = primeSum(10)
uniquePermutations(perms)
uniquePermutations2(perms)

22
src/Assignment6/Ex3.sc Normal file
View File

@ -0,0 +1,22 @@
val cities = List("Paris", "London", "Berlin", "Lausanne")
val relatives = List("Grandma", "Grandpa", "Aunt Lottie", "Dad")
val travellers = List("Pierre-Andre", "Rachel")
def generatePostcards(cities: List[String], relatives: List[String], travellers: List[String]): List[String] = {
for (t <- travellers;
r <- relatives;
c <- cities) yield s"Dear $r, Wish you were here in $c! Love, $t"
}
def generatePostcards2(cities: List[String], relatives: List[String], travellers: List[String]): List[String] = {
for (t <- travellers;
r <- relatives;
c <- cities;
if r.startsWith("G")) yield s"Dear $r, Wish you were here in $c! Love, $t"
}
val cards: List[String] = generatePostcards(cities, relatives, travellers)
println(cards.mkString("\n"))
val cards2: List[String] = generatePostcards2(cities, relatives, travellers)
println(cards2.mkString("\n"))

39
src/Assignment6/Ex4.sc Normal file
View File

@ -0,0 +1,39 @@
def inCheck(q1: (Int, Int), q2: (Int, Int)) =
q1._1 == q2._1 || // same row
q1._2 == q2._2 || // same column
(q1._1 - q2._1).abs == (q1._2 - q2._2).abs // on diagonal
def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) =
queens forall (q => !inCheck(queen, q))
def queens(n: Int): List[List[(Int, Int)]] = {
def placeQueens(k: Int): List[List[(Int, Int)]] =
if (k == 0)
List(List())
else
for {
queens <- placeQueens(k - 1)
column <- 1 to n
queen = (k, column)
if isSafe(queen, queens)
} yield queen :: queens
placeQueens(n)
}
def printChessBoard(solutions: List[List[(Int, Int)]]): String = {
val sols: List[String] = for ((sol, i) <- solutions.zipWithIndex) yield {
val lines: IndexedSeq[String] = for (y <- 1 to sol.length) yield {
val line: IndexedSeq[String] = {
for (x <- 1 to sol.length) yield {
if (sol contains (y, x)) "" else "_"
}
}
line.mkString("|", "|", "|")
}
s"Solution $i:\n" + lines.mkString("\n")
}
sols.mkString("\n\n")
}
println(printChessBoard(queens(4)))

View File

@ -0,0 +1,18 @@
(2 to 10).foreach(i =>
(2 to 10)
.filter(j => i % j == 0)
.foreach(j =>
println(s"$i is an integer multiple of $j")
)
)
val positions = for (
col <- 'a' to 'h';
row <- 1 to 8
) yield (col, row)
val whites = for (
col <- 'a' to 'h';
row <- 1 to 8;
if ((col - 'a' + row) % 2 == 0)
) yield (col, row)

40
src/Lesson6/Ex_6.1.sc Normal file
View File

@ -0,0 +1,40 @@
def filter[T](func: T => Boolean, list: List[T]): List[T] = {
list match {
case Nil => Nil
case e::rest if func(e) => e::filter(func, rest)
case _::rest => filter(func, rest)
}
}
def partition[T](func: T => Boolean, list: List[T]): (List[T], List[T]) = {
list match {
case Nil => (List.empty[T], List.empty[T])
case e::rest => {
val part = partition(func, rest)
if (func(e)) {
(e::part._1, part._2)
} else {
(part._1, e::part._2)
}
}
}
}
def partition[T](func: T => Boolean, list: List[T]): (List[T], List[T]) = {
list.foldRight((List.empty[T], List.empty[T]))(
(e: T, prev: (List[T], List[T])) => {
if (func(e)) {
(e::prev._1, prev._2)
} else {
(prev._1, e::prev._2)
}
}
)
}
val b = (1 to 10).toList
filter((x: Int) => x % 2 == 0, b)
partition((x: Int) => x % 2 == 0, b)

29
src/Lesson6/Primes.sc Normal file
View File

@ -0,0 +1,29 @@
def time(f: => Unit => Any): Long = {
val start = System.currentTimeMillis()
f()
val end = System.currentTimeMillis()
end - start
}
def timeVerbose(s: String)(f: => Unit => Any): Unit = {
println(s"[$s] Measuring time...")
val duration = time(f)
println(s"[$s] It took ${duration}ms")
}
def isPrime(i: Int): Boolean =
i match {
case i if i <= 1 => false
case 2 => true
case _ => !(2 until i).exists(x => i%x == 0)
}
def primeSum(max: Int)(isPrimeFunc: Int => Boolean): List[(Int, Int)] = {
for (i <- (1 to max).toList;
j <- (1 to max).toList;
if isPrimeFunc(i + j)) yield (i, j)
}
timeVerbose("Normal Prime"){
primeSum(1000)(isPrime)
}

View File

@ -0,0 +1,25 @@
val q: List[Int] = List(1, 2, 3)
val p: List[Int] = List(4, 5, 6)
// 1.
for (x <- q) yield x * 2
q.map(x => x * 2)
// 2.
for (x <- q if x != 2) yield x * 2
q.filter(x => x !=2).map(x => x * 2)
// 3.
for (x <- q;
y <- p) yield (x, y)
q.flatMap(x => p.map(y => (x, y)))
// 4.
for (x <- q if (x < 2);
y <- p) yield (x, y)
q.filter(x => x < 2).flatMap(x => p.map(y => (x, y)))
for (x <- 1 to 2;
y <- 'a' to 'b') yield (x, y)
(1 to 2).flatMap(x => ('a' to 'b').map(y => (x, y)))

13
src/Lesson6/Tuples.sc Normal file
View File

@ -0,0 +1,13 @@
def merge(x: List[Int], y: List[Int]): List[Int] = {
(x, y) match {
case (list, Nil) => list
case (Nil, list) => list
case (e1::rest1, e2::rest2) =>
if (e1 < e2) e1::merge(rest1, y)
else e2::merge(x, rest2)
}
}
val n1 = List(0, 2, 4, 6)
val n2 = List(1, 3, 5, 7)
merge(n1, n2)