Jay
Jay

Reputation: 51

creating an array with information contained in two other arrays

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]

Upvotes: 5

Views: 112

Answers (5)

thebugfinder
thebugfinder

Reputation: 334

You can pick the one you want (just swap the comment #):

class Array
    def multiply_times(how_many)
        r = []
        #how_many.length.times { |i| how_many[i].times { r << self[i] } }
        self.each_with_index { |e, i| how_many[i].times { r << e } }
        r
    end
end

p ['a', 'b', 'c'].multiply_times([3, 5, 2])
#=> ["a", "a", "a", "b", "b", "b", "b", "b", "c", "c"]

Upvotes: 1

Agis
Agis

Reputation: 33626

array = ["a", "b", "c"]
how_many = [2, 2, 2]

result = []

array.each_with_index do |item, index|
  how_many[index].times { result << item }
end

print result # => ["a", "a", "b", "b", "c", "c"]

Upvotes: 1

vacawama
vacawama

Reputation: 154563

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

Upvotes: 2

ksol
ksol

Reputation: 12235

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.

Upvotes: 3

David Grayson
David Grayson

Reputation: 87386

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]

Upvotes: 11

Related Questions