【问题标题】:Take two arrays of strings and return an array with the combinations of the items in them获取两个字符串数组并返回一个包含其中项目组合的数组
【发布时间】:2015-07-25 16:59:36
【问题描述】:

我需要获取两个数组并返回一个包含其中项目组合的数组,首先列出第一个项目。像这样:

combinations(["on","in"],["to","rope"])
# => ["onto","onrope","into","inrope"]

我已经写了一个方法来做到这一点,但在那之后,我不知道该去哪里。

【问题讨论】:

  • 不均匀数组大小的预期输出如下:combinations(["on","in"],["to","rope", "test"])

标签: arrays ruby


【解决方案1】:

使用Array#product:

["on","in"].product(["to","rope"]).map(&:join)
# => ["onto", "onrope", "into", "inrope"]

【讨论】:

  • 我会这样做。如果您详细说明数组乘积方法的作用,那就太好了。可能只是将它们显示为两个单独的步骤就足够了。
【解决方案2】:
def combinations(ary1, ary2)
  ary1.map {|i| ary2.map {|i2|  "#{i}#{i2}" }}.flatten
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2016-02-12
    • 2016-04-22
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    相关资源
    最近更新 更多