Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove range from an array

Tags:

ruby

I'm trying to find something equivalent to remove_range (which does not exist of course) as shown below. Seems there is no easy way to implement this functionality.

a = [0,2,8,2,4,5,]
b = a.remove_range(1,2) #remove items between index 1 and 2 ,inclusively
#expect b == [0,2,4,5]
b = a.remove_range(3,4)
#expect b == [0,2,8,5]

Please test at least above two cases before posting your solution :)

Suppose the size of the range is M, this operation should requires O(1) space and O(N-M) time complexity.

EDIT: I see people keep posting the a - a[range]. But it is not correct, that is to remove the elements exists in a[range], not to remove the the element belongs to range.

a - a[1..2] will return [0, 4, 5]. However,we want to keep the 3rd element which is 2.

like image 977
pierrotlefou Avatar asked Feb 11 '23 04:02

pierrotlefou


2 Answers

You can do some cool tricks with the Enumerable module:

a = [0, 2, 8, 2, 4, 5]
r = 1..2
a.reject.with_index { |v, i| r.include?(i) }  # => [0, 2, 4, 5]

Note that this does not modify the original array, but returns a new one. You can use reject! if you want to modify the array.

like image 152
David Grayson Avatar answered Feb 12 '23 17:02

David Grayson


# Use: array.slice!(range)
a = [0,2,8,2,4,5,]

a.slice!(1..2)
a # => [0, 2, 4, 5]

Or for indices range 3 to 4

a.slice!(3..4)
a # => [0, 2, 8, 5]
like image 24
Edgar Mkaka Joel Avatar answered Feb 12 '23 16:02

Edgar Mkaka Joel