给定大小为y的数组,其中包含大小为n的数组,如何使用Ruby返回所有逻辑组合? [英] Given an array of size y, containing arrays of size n, how can I return all logical combinations using Ruby?

查看:73
本文介绍了给定大小为y的数组,其中包含大小为n的数组,如何使用Ruby返回所有逻辑组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是处理 n 个集合,而我下面提供的代码恰好可以使用4个集合.

What I want to do is deal with n sets, while the code I provide below works with exactly 4 sets.

def show_combinations
  @combos = []
  ['A', 'no A'].each do |a|
    ['B', 'no B'].each do |b|
      ['C', 'no C'].each do |c|
        ['D', 'no D'].each do |d|
          @combos << [a, b, c, d]
        end
      end
    end
  end
end

如何重构以下代码以应对以下情况: 鉴于我有一个大小为y的数组,其中包含大小为n的数组,我想返回所有组合.重要的是要注意,每个子数组中只能有一个项目出现在结果中. (例如,完整的个人资料"也不能出现在未完成的个人资料"的搜索结果中)

How can I refactor this following code to deal with the following scenario: Given I have an array of size y containing arrays of size n, I want to return all the combinations. It's important to note that only one item in each of the sub arrays can be in the results. (Such as "Completed Profile" can't also be in the results with "Not completed profile")

背景:

用户可能有一些任务:例如,完整的个人资料"或设置电子邮件"或其他任何任务.这些任务可以这样表示:

A user might have some tasks: for example, "Complete Profile" or "Set Up Email" or whatever. Those tasks can be represented like this:

@task_states = [["Completed Profile, NOT Completed Profile"], ["Set up Email", "NOT set up Email"]]

然后,将@task_states传递到方法中,结果应为:

Then, passing @task_states into the method, the results should be this:

[
["Completed Profile", "Set up Email"],
["Completed Profile", "NOT set up Email"],
["NOT Completed Profile", "Set up Email"],
["NOT Completed Profile", "NOT Set up Email"]
]

所以代表所有组合的数组组成的数组.显然,完整的个人资料"也不能与未完成的个人资料"位于同一数组中.

So an array of arrays representing all the combinations. Obviously "Completed Profile" can't also be in the same array as "NOT Completed Profile," etc.

谢谢!

推荐答案

似乎要计算数组的笛卡尔积.计算笛卡尔积的方法被称为 Array#product :

It looks like you want to compute the cartesian product of the arrays. The method which computes the cartesian product is (not too surprisingly) called Array#product:

@task_states.first.product(*@task_states.drop(1))

例如,

['A', 'no A'].product(['B', 'no B'], ['C', 'no C'], ['D', 'no D'])
#=> [[   "A",    "B",    "C",    "D"],
#    [   "A",    "B",    "C", "no D"],
#    [   "A",    "B", "no C",    "D"],
#    [   "A",    "B", "no C", "no D"],
#    [   "A", "no B",    "C",    "D"],
#    [   "A", "no B",    "C", "no D"],
#    [   "A", "no B", "no C",    "D"],
#    [   "A", "no B", "no C", "no D"],
#    ["no A",    "B",    "C",    "D"],
#    ["no A",    "B",    "C", "no D"],
#    ["no A",    "B", "no C",    "D"],
#    ["no A",    "B", "no C", "no D"],
#    ["no A", "no B",    "C",    "D"],
#    ["no A", "no B",    "C", "no D"],
#    ["no A", "no B", "no C",    "D"],
#    ["no A", "no B", "no C", "no D"]]

这篇关于给定大小为y的数组,其中包含大小为n的数组,如何使用Ruby返回所有逻辑组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆