简体   繁体   中英

Multiplying within 2D array

I'm trying to get the product of a permutation of an array:

orig_arr = (89..99).to_a

perm = [[89, 90], [89, 91], [89, 92], [89, 93]...]

need = [[8010], [8099], [8188]...]

My best guess was to enumerate, but reduce doesn't function within each :

perm.each{|set| set.reduce(:*)}

Why doesn't this work? And, is it better to not create a 2D array, and go with a hash or matrix to solve this problem?

You can make it work by using Array#map instead of each :

orig_arr = (89..99).to_a
orig_arr.permutation(2).map { |set| [set.reduce(:*)] }
# => [[8010], [8099], [8188], [8277], [8366], [8455], . . . ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM