简体   繁体   English

查找数组的所有键唯一排列

[英]Find all key-unique permutations of an array

I have an array that looks something like this:我有一个看起来像这样的数组:

[["Sunday", [user1, user2]], ["Sunday", [user1, user4]], ["Monday", [user3, user2]]]

The array essentially has all permutations of a given day with a unique pair of users.该数组本质上具有给定日期的所有排列以及一对唯一用户。 I obtained it by running我通过运行获得它

%w[Su Mo Tu We Th Fr Sa].product(User.all_pairs)

where User.all_pairs is every unique pair of users.其中User.all_pairs是每对唯一的用户。

My goal now is to compose this set of nested arrays into schedules, meaning I want to find every permutation of length 7 with unique days.我现在的目标是将这组嵌套数组组合成时间表,这意味着我想找到每个长度为 7 的排列,并且具有独特的天数。 In other words, I want every potential week.换句话说,我想要每一个潜在的星期。 I already have every potential day, and I have every potential pair of users, now I just need to compose them.我已经拥有了每一个潜在的日子,我拥有每对潜在的用户,现在我只需要编写它们。

I have a hunch that the Array.permutation method is what I need, but I'm not sure how I'd use it in this case.我有一种预感,我需要Array.permutation方法,但我不确定在这种情况下如何使用它。 Or perhaps I should use Array.product ?或者我应该使用Array.product

If I understand you correctly, you want all possible weeks where there is one pair of users assigned to each day.如果我理解正确的话,您希望在所有可能的几周内每天分配一对用户。 You can do it like this:你可以这样做:

User.all_pairs.combination(7)

This will give you all possible ways of how you can pick 7 pairs and assign them to the days of the week.这将为您提供所有可能的方法来选择 7 对并将它们分配给一周中的几天。 But if you are asking for every possible week, then it also matters into which day is which pair assigned, and you also have to take every permutation of those 7 pairs:但是,如果您要求每个可能的一周,那么分配哪对哪一天也很重要,并且您还必须采用这 7 对的每一个排列:

User.all_pairs.combination(7).map{|week| week.permutation().to_a}.flatten(1)

Now this will give you all possible weeks, where every week is represented as array containing 7 pairs.现在这将为您提供所有可能的周,其中每周表示为包含 7 对的数组。 For example one of the weeks may look like this:例如,其中一个星期可能如下所示:

[(user1, user2), (user1, user3), (user2, user3), (user3, user4), (user1, user4), (user2, user4), (user3, user4)]

However the amount of the weeks will be huge!然而,周数将是巨大的! If you have n users, you will have k = n!/2 pairs, there is p = k! / (7! * (k - 7)!)如果您有n用户,您将有k = n!/2对,即p = k! / (7! * (k - 7)!) p = k! / (7! * (k - 7)!) ways of selecting 7 pairs and p * 7! p = k! / (7! * (k - 7)!)选择 7 对和p * 7! possible weeks.可能的几周。 If you have just 5 users, you get 1946482876800 possible weeks!如果您只有 5 个用户,则可能有 1946482876800 个星期! No matter what you are planning to do with it, it won't be possible.无论你打算用它做什么,它都不可能实现。

If you are trying to find the best schedule for a week, you can try to make some greedy algorithm.如果你想找到一周的最佳时间表,你可以尝试做一些贪心算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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