2

I have an array:

[1, 2, 3, 6, 8, 9, 10, 23, 34, 35, 36, 45, 50, 51, ...]

I'm trying to remove each group of consecutive numbers so I end up with:

[6, 23, 45, ...]

I am looking for anomalies in serial ids. Does anyone have suggestions?

My initial attempt only checks for the id before each element:

non_consecutive_ids = []
ids.each_with_index do |x, i|
  unless x == ids[i-1] + 1
    non_consecutive_ids << x
  end
end

The thing I think I was missing was to also check to see if the next element in the array is 1 more than the current.

5
  • 1
    Possible duplicate of Select consecutive integers from array in Ruby Commented Nov 20, 2018 at 18:24
  • would it not be 3, 6, 10, 23, 36, 45, 51? Commented Nov 20, 2018 at 18:24
  • What have you tried? Where is the work you have done so far in trying to solve this problem on your own? Why don't any of the many similar answered questions on stackoverflow answer the question for you? Commented Nov 20, 2018 at 18:26
  • @anothermh The answer to the possible duplicate you referenced has what I need, but the question is the opposite of what I was trying to do. It's also flagged as not a very good question. I searched, but most of the questions I found were not doing exactly what I was looking for. Will update my question with the code I first attempted with. Commented Nov 20, 2018 at 18:45
  • @JoshBrody That could be a resulting array, but not what I'm looking for. I really do want the result to exclude each entire group of consecutive numbers. Commented Nov 20, 2018 at 18:49

2 Answers 2

8

Other option:

array.chunk_while { |i, j| i + 1 == j }.select { |e| e.size == 1 }.flatten
#=> [6, 23, 45]

The good of Enumerable#chunk_while is that it takes two params. The core doc has just an example of a one-by-one increasing subsequence.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. Invariably, one can flip a coin to decide whether to use Enumerable#chunk_while or Enumerable#slice_when (a.slice_when { |a,b| b != a + 1 }...).
2

You can use select and check the surrounding values:

array.select.with_index{ |x, index| (array[index-1] != x-1) && (array[index+1] != x+1)}

1 Comment

array = [1,3,0]; arr.select.with_index{ |x, index| (array[index-1] != x-1) && (array[index+1] != x+1)} #=> [0]. The problem is when index #=> 0, array[index-1] #=> 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.