added midterm preparation
This commit is contained in:
36
src/MidTermPrep1/Ex3.sc
Normal file
36
src/MidTermPrep1/Ex3.sc
Normal file
@@ -0,0 +1,36 @@
|
||||
import scala.annotation.tailrec
|
||||
|
||||
def countTrue(bools: List[Boolean]): Int = {
|
||||
bools.foldLeft(0)((n, bool) => if (bool) n + 1 else n)
|
||||
}
|
||||
|
||||
countTrue(List(true, true, false, true, false, false))
|
||||
|
||||
def remDup[T](list: List[T]): List[T] = {
|
||||
list.foldRight(List.empty[T])((elem: T, res: List[T]) => {
|
||||
if (res.contains(elem)) res
|
||||
else elem::res
|
||||
})
|
||||
}
|
||||
|
||||
def remDup2[T](list: List[T]): List[T] = {
|
||||
list.foldLeft(List.empty[T])((res: List[T], elem: T) => {
|
||||
if (res.contains(elem)) res
|
||||
else res :+ elem
|
||||
})
|
||||
}
|
||||
|
||||
def remDup3[T](list: List[T]): List[T] = {
|
||||
@tailrec
|
||||
def helper(list: List[T], distinct: List[T]): List[T] = {
|
||||
list match {
|
||||
case head::rest if distinct.contains(head) => helper(rest, distinct)
|
||||
case head::rest => helper(rest, distinct :+ head)
|
||||
case Nil => distinct
|
||||
}
|
||||
}
|
||||
helper(list, List.empty[T])
|
||||
}
|
||||
|
||||
remDup(List(5,3,2,4,3,2,3,3)) // List(5,3,2,4)
|
||||
remDup(List("hello", "youpi", "hello", "hello")) // List("hello", "youpi")
|
||||
Reference in New Issue
Block a user