scala - how to remove sub list -


how can remove occurrences of sublist list, eg

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

should remove occurrences of (4, 5) (in order!), returns

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

a recursive solution using 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) }  // 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:

  • (thanks @corvus_192) reverting using indexofslice version instead of using diff, ignores sublist order.
  • (thanks @the archetypal paul) using patch cleaner removal of sublist

Comments

Popular posts from this blog

Python Pandas join aggregated tables -

java - Static nested class instance -

java - How to access payload from REST 404 response in Camel cxfrs? -