如何在 Scala 中对可变长度的重复序列进行分组 [英] How to group a variable-length, repeating sequence in Scala
本文介绍了如何在 Scala 中对可变长度的重复序列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组以某种模式重复的整数:
I have a collection of ints that repeat themselves in a pattern:
val repeatingSequence = List(1,2,3,1,2,3,4,1,2,1,2,3,4,5)
当模式重复时,我想将列表分割;在这种情况下,当序列回到 1 时:
I'd like to section that List up when the pattern repeats itself; in this case, when the sequence goes back to 1:
val groupedBySequence = List(List(1,2,3), List(1,2,3,4), List(1,2), List(1,2,3,4,5))
请注意,当序列跳回 1 时我正在分组,但序列可以是任意长度.我和我的同事通过添加一个名为groupWhen"的额外方法解决了这个问题
Notice that I'm grouping when the sequence jumps back to 1, but that the sequence can be of arbitrary length. My colleague and I have solved it by adding an additional method called 'groupWhen'
class IteratorW[A](itr: Iterator[A]) {
def groupWhen(fn: A => Boolean): Iterator[Seq[A]] = {
val bitr = itr.buffered
new Iterator[Seq[A]] {
override def hasNext = bitr.hasNext
override def next = {
val xs = collection.mutable.ListBuffer(bitr.next)
while (bitr.hasNext && !fn(bitr.head)) xs += bitr.next
xs.toSeq
}
}
}
}
implicit def ToIteratorW[A](itr: Iterator[A]): IteratorW[A] = new IteratorW(itr)
> repeatingSequence.iterator.groupWhen(_ == 1).toSeq
List(List(1,2,3), List(1,2,3,4), List(1,2), List(1,2,3,4,5))
然而,我们都觉得收藏库中潜藏着更优雅的解决方案.
However, we both feel like there's a more elegant solution lurking in the collection library.
推荐答案
给定一个迭代器 itr
,这可以解决问题:
Given an iterator itr
, this will do the trick:
val head = iter.next()
val out = (
Iterator continually {iter takeWhile (_ != head)}
takeWhile {!_.isEmpty}
map {head :: _.toList}
).toList
这篇关于如何在 Scala 中对可变长度的重复序列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文