scala - How to remove multiple indices from a ListBuffer (in a fast way)? -
<>
Is it a good way to remove more than one index from the listbuff in Scala?
Example:
val indicesToDelete = list (4, 1) wall buffer = listbuffer (a, b, c, d, e)
Result:
list buffer (b, c, e)
I could not find a pre-defined function which works.
Any index can sort and remove the elements starting from the highest index etc, so there will be no complexity. But sorting is needed O (n * log n)
Is there a fast way (probably some pre-defined I missed)?
Update 1: Elements should be removed in the existing list buffer object, no new ListBuffer object should be created.
Unlike others, I'm assuming that you want to do your work in these places because you mention If there is a concern about index reencurring if you are worried about all of the sort then
1) Instead of a list stick an index to be extracted in the set of viewing time. A hash set or bit set will be appropriate depending on the category of the index 2) Move the list buffer into reverse order that is in a two-set set.
scala & gt; Val buffer = listbuffer ("a", "b", "c", "d", "e") buffer: scala.collection.mutable.ListBuffer [java.lang.String] = ListBuffer (a, b, c, D, E) Scala & gt; Val Indexedeliet = Bitset (4, 1) IndexAandLight: Scala.Collection.mable.betset = bitset (1, 4) scale & gt; For (0 by -1 (buffer size -1) for (0) by -1) Remove the buffer I (in indextodilate) I scala & gt; Buffer Rage 19: Scala. Calling. Listbuffer [java.lang.String] = ListBuffer (A, C, D)
Note that when it extracted the N log n sort indesthes, that it is not creating a linear algorithm It is not cheap to remove from the array-like structure. High indexes have to be copied down on each delete.
To line up the index, you need to have more hairline, you need 1) Moving in the forward direction is a copy of the non-removed elements, based on the bottom, on the number that You have removed so far. When you're done 2) Remove the top n elements where n is the number you have deleted.
scala & gt; Val buffer = listbuffer ("a", "b", "c", "d", "e") buffer: scala.collection.mutable.ListBuffer [java.lang.String] = ListBuffer (a, b, c, D, E) Scala & gt; Val Indexedeliet = Bitset (4, 1) IndexAandLight: Scala.Collection.mable.betset = bitset (1, 4) scale & gt; Var removed = 0 deleted: int = 0 scala> (I & lt; - 0 until buffer size). If (index toadelete i) {| Destroyed + = 1 | } And if (deleted> gt; 0) {| Buffer (i - deleted) = buffer (i). } Scala & gt; } Scala & gt; Buffer trim and removed skeleton & gt; Buffer res0: scala.collection.mutable.ListBuffer [java.lang.String] = list buffer (A, C, D)