Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have an array with sorted integers

array = [1,4,10,14,22]

i would like to create from array before an

array_with_ranges = [[0..1],[2..4],[5..10],[11..14],[15..22]]

i cant create a right iterator, i'm newbie in rails. In every ranges i have end_range value, but don't know how to set a start_range value? in most ranges in array_with_ranges the start_range is a end_range before +1 (except [0..1])

any solutions or ideas?

thank you for answers.

p.s.: happy new 2015 year

share|improve this question

3 Answers 3

up vote 2 down vote accepted

Add a helper value of -1, later on remove it.

array = [1,4,10,14,22]
array.unshift(-1)
ranges = array.each_cons(2).map{|a,b| a+1..b} #=>[0..1, 2..4, 5..10, 11..14, 15..22]

array.shift
share|improve this answer
    
thank you! brilliant solution) –  anndrew78 Jan 13 at 19:51

Just keeping track of the previous value takes care of it:

2.1.5 :001 > array = [1,4,10,14,22]
 => [1, 4, 10, 14, 22] 
2.1.5 :002 > previous = 0
 => 0 
2.1.5 :003 > array.map { |i| rng = previous..i; previous = i + 1; rng }
 => [0..1, 2..4, 5..10, 11..14, 15..22] 

I imagine there's a slicker way to do it though.

edit: Of course there is, building on @steenslag's answer:

2.1.5 :001 > array = [1, 4, 10, 14, 22]
 => [1, 4, 10, 14, 22] 
2.1.5 :002 > ([-1] + array).each_cons(2).map { |a,b| (a + 1)..b }
 => [0..1, 2..4, 5..10, 11..14, 15..22] 
share|improve this answer

You can iterate on all elements of the array and save the previous value in the external variable, like this:

last = -1 
array.collect {|x| prev = last; last = x; (prev+1..x)}
share|improve this answer
    
excellent!it's a good method to do it. –  user3673267 Jan 12 at 3:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.