Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
|
|
@ -0,0 +1,33 @@
|
|||
object LongestIncreasingSubsequence extends App {
|
||||
val tests = Map(
|
||||
"3,2,6,4,5,1" -> Seq("2,4,5", "3,4,5"),
|
||||
"0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> Seq("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15")
|
||||
)
|
||||
|
||||
def lis(l: Array[Int]): Seq[Array[Int]] =
|
||||
if (l.length < 2) Seq(l)
|
||||
else {
|
||||
def increasing(done: Array[Int], remaining: Array[Int]): Seq[Array[Int]] =
|
||||
if (remaining.isEmpty) Seq(done)
|
||||
else
|
||||
(if (remaining.head > done.last)
|
||||
increasing(done :+ remaining.head, remaining.tail)
|
||||
else Nil) ++ increasing(done, remaining.tail) // all increasing combinations
|
||||
|
||||
val all = (1 to l.length)
|
||||
.flatMap(i => increasing(l take i takeRight 1, l.drop(i + 1)))
|
||||
.sortBy(-_.length)
|
||||
all.takeWhile(_.length == all.head.length) // longest of all increasing combinations
|
||||
}
|
||||
|
||||
def asInts(s: String): Array[Int] = s split "," map (_.toInt)
|
||||
|
||||
assert(tests forall {
|
||||
case (given, expect) =>
|
||||
val allLongests: Seq[Array[Int]] = lis(asInts(given))
|
||||
println(
|
||||
s"$given has ${allLongests.length} longest increasing subsequences, e.g. ${
|
||||
allLongests.last.mkString(",")}")
|
||||
allLongests.forall(lis => expect.contains(lis.mkString(",")))
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
def powerset[A](s: List[A]) = (0 to s.size).map(s.combinations(_)).reduce(_++_)
|
||||
def isSorted(l:List[Int])(f: (Int, Int) => Boolean) = l.view.zip(l.tail).forall(x => f(x._1,x._2))
|
||||
def sequence(set: List[Int])(f: (Int, Int) => Boolean) = powerset(set).filter(_.nonEmpty).filter(x => isSorted(x)(f)).toList.maxBy(_.length)
|
||||
|
||||
sequence(set)(_<_)
|
||||
sequence(set)(_>_)
|
||||
Loading…
Add table
Add a link
Reference in a new issue