Ruby - creating an array by multiplying multiple occurrences

I want to create an array of size 100 so that the values ​​are displayed in the X number of occurrences defined in another array.

So, the following arrays:

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

Creates a new array containing 5 times the value 'text1', 50 times the value 'text6', etc.

+4
source share
3 answers

Try this one

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

First, I connect each row with its integer, then iterate over these pairs and create an array of n times the string s. flat_mapinstead of a simple one mapit does the trick of not having a multidimensional array.

+7
source

You can do:

arr1.zip(arr2).map {|s,x| [s]*x}

[[s,s,s..],[s2,s2,s2...]]. , :

arr1.zip(arr2).flat_map {|s,x| [s]*x}

, zip transpose , :

[arr1, arr2].transpose.flat_map { |s,x| [s] * x }
+6

#

arr1.flat_map.with_index { |s,i| [s].cycle.take arr2[i] }

#

arr2.flat_map.with_index { |n,i| [].fill arr1[i], 0...n }

# *

arr1.flat_map.with_index { |s,i| [s] * arr2[i] }

#

arr1.map.with_index { |s,i| [].insert 0, [s] * arr2[i] }.flatten
+2
source

Source: https://habr.com/ru/post/1682006/


All Articles