ruby - Create array of ranges with loop, combine ranges to array of Fixnum -
i'm looping through set of foo
have starting_postion
, size
if ! foo.position.nil? @foo_top = foo.position + foo.size - 1 @occupied_array = (foo.position..@foo_top) end
i see reassigning array on each loop. end goal combine of ranges in array of fixnums can compare.
should just: @occupied_array += (foo.position..@foo_top)
, @occupied_array.to_a
later?
thanks
if understand correctly, have array of foo
objects each represent range of integers start , length. , want produce single array of integers representing values covered of foo
objects.
if that's true, try following:
foo = struct.new(:position, :size) all_the_foos = [foo.new(10,3), foo.new(3,3), foo.new(15,5)] p all_the_foos.flat_map { |f| (f.position...(f.position+f.size)).to_a }.uniq.sort #=> [3, 4, 5, 10, 11, 12, 15, 16, 17, 18, 19]
not sure whether #uniq
or #sort
desired, remove necessary.
Comments
Post a Comment