Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - create array by multiplying set of occurrences

Tags:

arrays

ruby

I want to create an array of size of 100 such that the values will appear X number of occurrences defined in another array.

So the below arrays:

arr1 = ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
arr2 = [5, 5, 10, 10, 20, 50] 

Will create a new array that contains 5 times the value 'text1', 50 times the value 'text6', etc.

like image 549
Tom Avatar asked Dec 06 '22 14:12

Tom


1 Answers

Try this one

arr1.zip(arr2).flat_map { |s, n| Array.new(n) { s } }

I first pair each string with its integer, then iterate over these pairs and create an array of n times string s. flat_map instead of simple map does the trick to not have a multidimensional array.

like image 164
Ursus Avatar answered Jan 08 '23 05:01

Ursus