From 4eba7f3587def86a874f8122f7796edb083a63cf Mon Sep 17 00:00:00 2001 From: LordBaryhobal Date: Tue, 8 Apr 2025 15:29:08 +0200 Subject: [PATCH] added assignment 6 ex 2 --- src/Assignment6/Ex2.sc | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/Assignment6/Ex2.sc diff --git a/src/Assignment6/Ex2.sc b/src/Assignment6/Ex2.sc new file mode 100644 index 0000000..2311c61 --- /dev/null +++ b/src/Assignment6/Ex2.sc @@ -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) \ No newline at end of file