我怎樣才能從列表中刪除子表的所有事件,如如何刪除子列表
List(1, 2, 3, 4, 5, 6, 7, 4, 8, 9, 10, 5).removeSubList(4, 5)
應該刪除所有出現的(4,5)(順序),所以它返回
List(1, 2, 3, 6, 7, 4, 8, 9, 10, 5)
我怎樣才能從列表中刪除子表的所有事件,如如何刪除子列表
List(1, 2, 3, 4, 5, 6, 7, 4, 8, 9, 10, 5).removeSubList(4, 5)
應該刪除所有出現的(4,5)(順序),所以它返回
List(1, 2, 3, 6, 7, 4, 8, 9, 10, 5)
使用indexOfSlice
遞歸溶液:
def removeSubList(l: List[Int], sublist: List[Int]): List[Int] = l.indexOfSlice(sublist) match {
case -1 => l
case index => removeSubList(l.patch(index, Nil, sublist.length), sublist)
}
// all of these print List(1 ,2 ,3):
println(removeSubList(List(1,2,3), List(4,5)))
println(removeSubList(List(1,2,3,4,5), List(4,5)))
println(removeSubList(List(4,5,1,2,3), List(4,5)))
println(removeSubList(List(4,5,1,2,4,5,3), List(4,5)))
EDITED:
indexOfSlice
版本,而不是使用diff
,而忽略子列表順序。patch
對清潔去除子表的使用Tzach瑣想法不同的實現:
def removeSubList[T](list: List[T], sublist: List[T]): List[T] =
if (list.containsSlice(sublist))
removeSubList(list.diff(sublist), sublist)
else list
我不這麼認爲 - OP希望(4,5)除去的所有實例,而'列表(4,5,1,4,5)爲.diff(名單(4,5))會產生'List(1,4,5)' –
上Tzach瑣想法變但假定的OP想要的結果不包括曾經給定的子表。處理的情況下sublist
是空
/**
* Return `s` with no occurrence of `target` present
*
* @param s
* @param target
* @return The sequence free of any occurrence of the target slice
*/
def removeCompletely[E](s: Seq[E], target: Seq[E]): Seq[E] = {
if (s.isEmpty || target.isEmpty)
s
else
removeCompletely0(s, target)
}
private def removeCompletely0[E](s: Seq[E], target: Seq[E]): Seq[E] = {
val sliceIdx = s.indexOfSlice(target)
if (sliceIdx >= 0) {
val patched = s.patch(sliceIdx, s take 0, target.size)
removeCompletely0(patched, target)
}
else {
s
}
}
'removeSubList(List(1,5,4,5,2),List(4,5))'返回List(1) ,2)''而不是'List(1,5,2)' –
謝謝@ corvus_192 - 使用'indexOfSlice'恢復到原始版本 –
您可以使用'patch'取出子列表 –