查找Ruby中数组的每个排列,包括子数组的排列 [英] Find every permutation of an array in Ruby, including permutations with sub arrays
本文介绍了查找Ruby中数组的每个排列,包括子数组的排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑一个数组:[4, 6, 9]
要求所有排列:(一位,两位和三位数)
Require all the permutations: (one, two and three digit ones)
[[9],
[6],
[4],
[9, 6],
[9, 4],
[6, 9],
[6, 4],
[4, 9],
[4, 6],
[9, 6, 4],
[9, 4, 6],
[6, 9, 4],
[6, 4, 9],
[4, 9, 6],
[4, 6, 9]]
推荐答案
记录此问题和我自己的发现,因为我在搜索时没有找到足够简单的东西.也许这可以帮助某人:
Recording this question and my own finding as I didn't find anything simple enough while searching. Perhaps this may help someone:
a = [4, 6, 9]
(1..a.length).flat_map { |n| a.permutation(n).to_a }
对于每种组合,只需切换方法,如下所示:
And for every combination, just switch the method, like so:
a = [4, 6, 9]
(1..a.length).flat_map { |n| a.combination(n).to_a }
这篇关于查找Ruby中数组的每个排列,包括子数组的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文