How to remove a range from an array

I am trying to find something equivalent remove_range(which, of course, does not exist), as shown below. There seems to be 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]

Before submitting a solution, please check at least two cases :)

Assume that the size of the range is M, this operation should take O (1) time and O (NM) time complexity.

EDIT: I see people keep posting a - a[range]. But this is not true, that is, delete elements in [range], and not delete an element belonging to a range.

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

+4
source share
7 answers

Enumerable:

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

, , . reject!, .

+3

. , :

2.0.0-p353 :001 > ar = [0,2,8,2,4,5]
=> [0, 2, 8, 2, 4, 5] 
2.0.0-p353 :002 > ar - ar[2..3]
=> [0, 4, 5] 
+1
class Array
  def remove_range(sp, ep)
    raise ArgumentError if sp < 0 || ep > size - 1
    slice(0...sp).concat(slice(ep+1..-1))
  end
end

Thanks to Carey Swoveland for his good advice.

+1
source
class Array
  def remove_range(f,l)
    self[0..f-1].concat(self[l+1..-1])
  end
end

a = [0,2,8,2,4,5]
b = a.remove_range(1,2)
[0, 2, 4, 5]
c = a.remove_range(3,4)
[0, 2, 8, 5]
+1
source
# Use: array.slice!(range)
a = [0,2,8,2,4,5,]

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

Or for indices from 3 to 4

a.slice!(3..4)
a # => [0, 2, 8, 5]
+1
source
a = [0,2,8,2,4,5]    
j = 1

(3..4).each do |i|
    j == 1 ? a.delete_at(i) : a.delete_at(i-1)
    j += 1
end

b = a
[0, 2, 8, 5]
0
source

I tried something scared with the help of string manipulations. I think this is O (4 * M), although if it is even a thing!

a.join.gsub(/#{a.join[1..2]}/,'').split('').map{|i| i.to_i}
=> [0, 2, 4, 5]
a.join.gsub(/#{a.join[3..4]}/,'').split('').map{|i| i.to_i}
=> [0, 2, 8, 5]
0
source

All Articles