从多个数组创建组(子数组的顺序很重要)

时间:2018-10-26 23:54:28

标签: arrays ruby algorithm data-structures permutation

我有三个数组。我想将它们三个结合起来,但是顺序很重要,并且我不想返回所有排列。例如:

STATE = [ 'Pennsylvania' ]
COUNTY = [ 'Bucks', 'Montgomery']
PROFESSION = ['Doctor', 'Firefighter', 'Teacher']

预期输出为:

[
  ['Pennsylvania', 'Bucks', 'Doctor'],
  ['Pennsylvania', 'Bucks', 'Firefighter'],
  ['Pennsylvania', 'Bucks', 'Teacher'],

  ['Pennsylvania', 'Montgomery', 'Doctor'],
  ['Pennsylvania', 'Montgomery', 'Firefighter'],
  ['Pennsylvania', 'Montgomery', 'Teacher']
]

就是这样。国家永远是第一项。县永远是第二项。职业将始终是第三项,并且按照该特定顺序。不应重复。

州和县以及专业的列表将继续增长。但是它将遵循相同的模式。

这些都是错误的:

['Bucks', 'Pennsylvania', 'Doctor']
['Teacher', 'Montgomery', 'Pennsylvania']
['Pennsylvania', 'Bucks', 'Montgomery']

那我尝试了什么?我认为也许使用排列将是一个很好的工具。但是您猜到了,它创造了每种可能的组合。因此,我尝试使用惰性迭代器来限制结果:

( STATE + COUNTY + PROFESSION ).permutation(3).lazy.first(10)
 => [["Pennsylvania", "Bucks", "Montgomery"], ["Pennsylvania", "Bucks", "Doctor"], ["Pennsylvania", "Bucks", "Firefighter"], ["Pennsylvania", "Bucks", "Teacher"], ["Pennsylvania", "Montgomery", "Bucks"], ["Pennsylvania", "Montgomery", "Doctor"], ["Pennsylvania", "Montgomery", "Firefighter"], ["Pennsylvania", "Montgomery", "Teacher"], ["Pennsylvania", "Doctor", "Bucks"], ["Pennsylvania", "Doctor", "Montgomery"]] 

但是正如您所看到的,我想要的顺序没有保留在then子数组中,这也很容易出错,因为每个数组的长度都是可变的,并且会不断增长。

在Ruby中解决此问题的干净方法是什么?

2 个答案:

答案 0 :(得分:2)

使用Array#product

STATE.product(COUNTY, PROFESSION)
 => [["Pennsylvania", "Bucks", "Doctor"],
     ["Pennsylvania", "Bucks", "Firefighter"],
     ["Pennsylvania", "Bucks", "Teacher"],
     ["Pennsylvania", "Montgomery", "Doctor"],
     ["Pennsylvania", "Montgomery", "Firefighter"],
     ["Pennsylvania", "Montgomery", "Teacher"]]

答案 1 :(得分:2)

您要查找的是列表的 product ,而不是排列功能为您提供的组合。您的代码甚至会返回诸如["Teacher", "Firefighter", "Montgomery"]之类的东西,而您有两个职业。值得庆幸的是,Ruby数组提供了product function

STATE.product(COUNTY, PROFESSION)
=> [["Pennsylvania", "Bucks", "Doctor"], ["Pennsylvania", "Bucks", "Firefighter"], ["Pennsylvania", "Bucks", "Teacher"], ["Pennsylvania", "Montgomery", "Doctor"], ["Pennsylvania", "Montgomery", "Firefighter"], ["Pennsylvania", "Montgomery", "Teacher"]]

列表A,B和C的乘积将返回三个元素的所有不同列表,每个列表分别包含A,B和C中的一个元素。将其与您调用的permutation函数进行比较,该函数将三个列表串联在一起,并为您提供统一列表中的三个不同元素 的所有组合。连接时,将不需要的元素分开。