Rikkas
Rikkas

Reputation: 582

Sorting an array by corresponding ranges

My purpose is to populate an array from list:

list = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 12, 13, 15]

in an order following this:

The correct output should be:

solution(list)
# => [-6, [-3, -2, -1, 0, 1], [3, 4, 5], [7, 8, 9, 10], [12, 13], 15]  

My code and my output is below.

def solution(list)
  result = []
  idx = 0
  loop do
    range = []
    loop do
      if list[idx+1] - list[idx] == 1
        range << list[idx]
        idx += 1
      else
        result << list[idx]
        idx += 1
        break
      end
    end
    result << range
  break if idx == list.size - 1
  end
  result
end 

solution(list)
# => [-6, [], 1, [-3, -2, -1, 0], 5, [3, 4], 10, [7, 8, 9], 13, [12]]

The code is not correct. Can you tell me what I am missing?

Upvotes: 2

Views: 62

Answers (1)

sawa
sawa

Reputation: 168091

You're missing chunk_while.

list.chunk_while{|a, b| a.next == b}.map{|a| a.one? ? a.first : a}
# => [-6, [-3, -2, -1, 0, 1], [3, 4, 5], [7, 8, 9, 10], [12, 13], 15]

Upvotes: 2

Related Questions