added assignment 6 ex 2
This commit is contained in:
parent
76a4f50075
commit
4eba7f3587
38
src/Assignment6/Ex2.sc
Normal file
38
src/Assignment6/Ex2.sc
Normal 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)
|
Loading…
x
Reference in New Issue
Block a user