Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def mycomb[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(el <- l;
- sl <- mycomb(n-1, l dropWhile { _ != el } ))
- yield el :: sl
- }
- def comb[T](n: Int, l: List[T]): List[List[T]] = mycomb(n, l.removeDuplicates)
- > comb(3, List(1,2,3))
- > List[List[Int]] = List(
- List(1, 1, 1), List(1, 1, 2), List(1, 1, 3), List(1, 2, 2),
- List(1, 2, 3), List(1, 3, 3), List(2, 2, 2), List(2, 2, 3),
- List(2, 3, 3), List(3, 3, 3))
- > comb(6, List(1,2,1,2,1,2,1,2,1,2))
- > List[List[Int]] = List(
- List(1, 1, 1, 1, 1, 1), List(1, 1, 1, 1, 1, 2), List(1, 1, 1, 1, 2, 2),
- List(1, 1, 1, 2, 2, 2), List(1, 1, 2, 2, 2, 2), List(1, 2, 2, 2, 2, 2),
- List(2, 2, 2, 2, 2, 2))
- def perm[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(el <- l.removeDuplicates;
- sl <- perm(n-1, l.slice(0, l.findIndexOf {_ == el}) ++ l.slice(1 + l.findIndexOf {_ == el}, l.size)))
- yield el :: sl
- }
- perm(2, List(1,2,2,2,1))
- List(List(2, 2), List(2, 1), List(1, 2), List(1, 1))
- List(
- List(1, 2), List(1, 2), List(1, 2), List(2, 1),
- List(2, 1), List(2, 1), List(2, 1), List(2, 1),
- List(2, 1), List(1, 2), List(1, 2), List(1, 2)
- )
- //P26
- def combinations[A](n:Int, xs:List[A]):List[List[A]]={
- def lift[A](xs:List[A]):List[List[A]]=xs.foldLeft(List[List[A]]())((ys,y)=>(List(y)::ys))
- (n,xs) match {
- case (1,ys)=> lift(ys)
- case (i,xs) if (i==xs.size) => xs::Nil
- case (i,ys)=> combinations(i-1,ys.tail).map(zs=>ys.head::zs):::combinations(i,ys.tail)
- }
- }
- def mycomb[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(el <- l;
- sl <- mycomb(n-1, l))
- yield el :: sl
- }
- def perm[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(el <- l;
- sl <- perm(n-1, l filter (_ != el)))
- yield el :: sl
- }
- def perm[T](n: Int, l: List[T]): List[List[T]] = {
- def perm1[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(el <- l;
- (hd, tl) = l span (_ != el);
- sl <- perm(n-1, hd ::: tl.tail))
- yield el :: sl
- }
- perm1(n, l).removeDuplicates
- }
- def comb[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(i <- (0 to (l.size - n)).toList;
- l1 = l.drop(i);
- sl <- comb(n-1, l1.tail))
- yield l1.head :: sl
- }
- def comb[T](n: Int, l: List[T]): List[List[T]] = {
- def comb1[T](n: Int, l: List[T]): List[List[T]] =
- n match {
- case 0 => List(List())
- case _ => for(i <- (0 to (l.size - n)).toList;
- l1 = l.drop(i);
- sl <- comb(n-1, l1.tail))
- yield l1.head :: sl
- }
- comb1(n, l).removeDuplicates
- }
Add Comment
Please, Sign In to add comment