Just another update
This commit is contained in:
parent
a25938f123
commit
00a190b0a6
6591 changed files with 94363 additions and 23227 deletions
|
|
@ -1,2 +1,8 @@
|
|||
scala> (0 to 4 toList) combinations(3) toList
|
||||
res1: List[List[Int]] = List(List(0, 1, 2), List(0, 1, 3), List(0, 1, 4), List(0, 2, 3), List(0, 2, 4), List(0, 3, 4), List(1, 2, 3), List(1, 2, 4), List(1, 3, 4), List(2, 3, 4))
|
||||
def combs[A](n: Int, l: List[A]): Iterator[List[A]] = n match {
|
||||
case _ if n < 0 || l.lengthCompare(n) < 0 => Iterator.empty
|
||||
case 0 => Iterator(List.empty)
|
||||
case n => l.tails.flatMap({
|
||||
case Nil => Nil
|
||||
case x :: xs => combs(n - 1, xs).map(x :: _)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
16
Task/Combinations/Scala/combinations-3.scala
Normal file
16
Task/Combinations/Scala/combinations-3.scala
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
def combs[A](n: Int, xs: List[A]): Stream[List[A]] =
|
||||
combsBySize(xs)(n)
|
||||
|
||||
def combsBySize[A](xs: List[A]): Stream[Stream[List[A]]] = {
|
||||
val z: Stream[Stream[List[A]]] = Stream(Stream(List())) ++ Stream.continually(Stream.empty)
|
||||
xs.toStream.foldRight(z)((a, b) => zipWith[Stream[List[A]]](_ ++ _, f(a, b), b))
|
||||
}
|
||||
|
||||
def zipWith[A](f: (A, A) => A, as: Stream[A], bs: Stream[A]): Stream[A] = (as, bs) match {
|
||||
case (Stream.Empty, _) => Stream.Empty
|
||||
case (_, Stream.Empty) => Stream.Empty
|
||||
case (a #:: as, b #:: bs) => f(a, b) #:: zipWith(f, as, bs)
|
||||
}
|
||||
|
||||
def f[A](x: A, xsss: Stream[Stream[List[A]]]): Stream[Stream[List[A]]] =
|
||||
Stream.empty #:: xsss.map(_.map(x :: _))
|
||||
2
Task/Combinations/Scala/combinations-4.scala
Normal file
2
Task/Combinations/Scala/combinations-4.scala
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
scala> (0 to 4 toList) combinations(3) toList
|
||||
res1: List[List[Int]] = List(List(0, 1, 2), List(0, 1, 3), List(0, 1, 4), List(0, 2, 3), List(0, 2, 4), List(0, 3, 4), List(1, 2, 3), List(1, 2, 4), List(1, 3, 4), List(2, 3, 4))
|
||||
Loading…
Add table
Add a link
Reference in a new issue