added final exam preparation
This commit is contained in:
26
src/FinalPrep1/Ex1.sc
Normal file
26
src/FinalPrep1/Ex1.sc
Normal file
@@ -0,0 +1,26 @@
|
||||
def insertion[T](x: T, xs: List[T]): List[List[T]] = {
|
||||
return (0 to xs.length).map((i: Int) => {
|
||||
val p = xs.splitAt(i)
|
||||
p._1 ::: (x :: p._2)
|
||||
}).toList
|
||||
|
||||
def buildInsertions(x: T, xs: List[T], before: List[T]): List[List[T]] = {
|
||||
xs match {
|
||||
case Nil => (before :+ x) :: Nil
|
||||
case head::tail => (before ::: (x :: xs)) :: buildInsertions(x, tail, before :+ head)
|
||||
}
|
||||
}
|
||||
buildInsertions(x, xs, Nil)
|
||||
}
|
||||
|
||||
insertion(1, List(2,3,4))
|
||||
|
||||
def permutation[T](xs: List[T]): List[List[T]] = {
|
||||
xs match {
|
||||
case head::tail => permutation(tail) flatMap (perm => insertion(head, perm))
|
||||
case _ => List(xs)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
permutation(List(1,2,3))
|
||||
Reference in New Issue
Block a user