0

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)}

Comments

0

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] 

Comments

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.