RosettaCodeData/Task/Longest-common-subsequence/Scala/longest-common-subsequence-1.scala

13 lines
415 B
Scala
Raw Permalink Normal View History

2019-09-12 10:33:56 -07:00
def lcsLazy[T](u: IndexedSeq[T], v: IndexedSeq[T]): IndexedSeq[T] = {
def su = subsets(u).to(LazyList)
def sv = subsets(v).to(LazyList)
su.intersect(sv).headOption match{
case Some(sub) => sub
case None => IndexedSeq[T]()
2016-12-05 22:15:40 +01:00
}
}
2019-09-12 10:33:56 -07:00
def subsets[T](u: IndexedSeq[T]): Iterator[IndexedSeq[T]] = {
u.indices.reverseIterator.flatMap{n => u.indices.combinations(n + 1).map(_.map(u))}
}