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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With