Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an array with information contained in two other arrays

Tags:

arrays

ruby

how can I buit an array using two arrays as follow:

name = [a, b, c]

how_many_of_each [3, 5, 2]

to get

my_array = [a, a, a, b, b, b, b, b, c, c]

like image 256
Jay Avatar asked Oct 02 '12 21:10

Jay


3 Answers

Use zip, flat_map, and array multiplication:

irb(main):001:0> value = [:a, :b, :c]
=> [:a, :b, :c]
irb(main):002:0> times = [3, 5, 2]
=> [3, 5, 2]
irb(main):003:0> value.zip(times).flat_map { |v, t| [v] * t }
=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]
like image 66
David Grayson Avatar answered Oct 04 '22 17:10

David Grayson


name.zip(how_many_of_each).inject([]) do |memo, (x, y)|
  y.times { memo << x}
  memo
end

=> [:a, :a, :a, :b, :b, :b, :b, :b, :c, :c]

EDIT: Oh well, there's better, see @David Grayson.

like image 38
ksol Avatar answered Oct 04 '22 17:10

ksol


This will do it in an easy to understand way:

my_array = []
name.count.times do |i|
    how_many_of_each[i].times { my_array << name[i] }
end
like image 38
vacawama Avatar answered Oct 04 '22 19:10

vacawama