3

想象一下combineSequences: (seqs: Set[Seq[Int]])Set[Seq[Int]]当第一个序列的最后一项与第二个序列的第一项匹配时组合序列的函数。例如,如果您有以下序列:

(1, 2)
(2, 3)
(5, 6, 7, 8)
(8, 9, 10)
(3, 4, 10)

结果combineSequences将是:

(5, 6, 7, 8, 8, 9, 10)
(1, 2, 2, 3, 3, 4, 10)

因为序列 1、2 和 5 组合在一起。如果多个序列可以组合以产生不同的结果,则决定是任意的。例如,如果我们有序列:

(1, 2)
(2, 3)
(2, 4)

有两个正确答案。任何一个:

(1, 2, 2, 3)
(2, 4)

或者:

(1, 2, 2, 4)
(2, 3)

我只能想到一个非常必要且相当不透明的实现。我想知道是否有人有更惯用的scala解决方案。我现在已经遇到过几次相关的问题。

4

1 回答 1

3

当然不是最优化的解决方案,但我已经追求可读性。

def combineSequences[T]( seqs: Set[Seq[T]] ): Set[Seq[T]] = {
  if ( seqs.isEmpty ) seqs
  else {
    val (seq1, otherSeqs) = (seqs.head, seqs.tail)
    otherSeqs.find(_.headOption == seq1.lastOption) match {
      case Some( seq2 ) => combineSequences( otherSeqs - seq2 + (seq1 ++ seq2) )
      case None =>
        otherSeqs.find(_.lastOption == seq1.headOption) match {
          case Some( seq2 ) => combineSequences( otherSeqs - seq2 + (seq2 ++ seq1) )
          case None => combineSequences( otherSeqs ) + seq1
        }
    }
  }
}

REPL测试:

scala> val seqs = Set(Seq(1, 2), Seq(2, 3), Seq(5, 6, 7, 8), Seq(8, 9, 10), Seq(3, 4, 10))
seqs: scala.collection.immutable.Set[Seq[Int]] = Set(List(1, 2), List(2, 3), List(8, 9, 10), List(5, 6, 7, 8), List(3, 4, 10))
scala> combineSequences( seqs )
res10: Set[Seq[Int]] = Set(List(1, 2, 2, 3, 3, 4, 10), List(5, 6, 7, 8, 8, 9, 10))
scala> val seqs = Set(Seq(1, 2), Seq(2, 3, 100), Seq(5, 6, 7, 8), Seq(8, 9, 10), Seq(100, 4, 10))
seqs: scala.collection.immutable.Set[Seq[Int]] = Set(List(100, 4, 10), List(1, 2), List(8, 9, 10), List(2, 3, 100), List(5, 6, 7, 8))
scala> combineSequences( seqs )
res11: Set[Seq[Int]] = Set(List(5, 6, 7, 8, 8, 9, 10), List(1, 2, 2, 3, 100, 100, 4, 10))
于 2013-09-20T13:07:24.573 回答