问题描述
我有一个字符串数组:
[ABC,GHI]
广告我希望所有的字母的组合,作为读取由左到右,即
[公司,啊,人工智能,BG,BH,商业智能,CG,CH,CI]
而不是
GA,GB,HA,等等。
同样,
[ABC,DEF,GHI]
应该产生
[ADG,ADH,阿迪,AEG,爱德华,AEI,AFG,AFH,AFI, BDG,BDH,
BDI,乞,BEH,被,BFG,BFH,BFI,CDG,鼎晖,CDI,CEG
CEH,CEI,CFG,CFHCFI]
而不是
DAG,GAD或建筑面积
这是你所需要的:
A = [ABC,DEF,GHI]
a.map(安培;:字符)。降低(安培;:产品).MAP(安培;:加入)
顺便说一句,你在你的例子输出做了一些错误,但绝不应先从E或根据您的规范中的F均被。所以我想,而不是ECH,ECI,FCG,FCH,FCI
你的意思CEH, CEI,CFG,CFH,CFI
。
编辑:
字符
返回一个枚举,而不是一个数组,并用Ruby 2.0之前那些版本没有产品
方法。因此,在这些版本中,只需要使用 to_a
是这样的:
a.map(安培;:字符).MAP(安培;:to_a)。降低(安培;:产品).MAP(安培;:加入)
I have an array of strings:
["ABC", "GHI"]
ad I want all the 'letter' combinations, as reads from left to right, i.e.
["AG", "AH", "AI", "BG", "BH", "BI", "CG", "CH", "CI"]
but not
"GA", "GB", "HA", etc.
Similarly,
["ABC", "DEF", "GHI"]
should generate
["ADG", "ADH", "ADI", "AEG", "AEH", "AEI", "AFG", "AFH", "AFI", "BDG", "BDH",
"BDI", "BEG", "BEH", "BEI", "BFG", "BFH", "BFI", "CDG", "CDH", "CDI", "CEG",
"CEH", "CEI", "CFG", "CFH" "CFI"]
but not
"DAG", "GAD" or "GFA"
This is what you need:
a = ["ABC","DEF", "GHI"]
a.map(&:chars).reduce(&:product).map(&:join)
By the way, you made some errors in your example output, there should never be strings starting with an E or an F according to your specification. So I suppose instead of "ECH", "ECI", "FCG", "FCH", "FCI"
you meant "CEH", "CEI", "CFG", "CFH", "CFI"
.
Edit:
chars
returns an Enumerator, not an array, and in Ruby versions before 2.0 those don't have a product
method. So in those versions, just use a to_a
like this:
a.map(&:chars).map(&:to_a).reduce(&:product).map(&:join)
这篇关于红宝石 - 如何从一个字符串数组的字母顺序可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!