gpt4 book ai didi

ruby-on-rails - 数组的所有变体

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:24 24 4
gpt4 key购买 nike

我有一个结构如下的数组:

  array = ["one","two","three","four"];

我怎样才能得到这个数组所有可能的变体,所有可能的长度 1-4:

  ar = [["one"]["two"]["three"]["four"]["one","two"]
["one","three"] ["one","three","four"]]

我觉得最后数组应该有4*4*4*4个元素

最佳答案

How can i get all possible variants of this array[...]

使用Array#combination :

array.combination(3).to_a

结果:

[["one", "two", "three"],
["one", "two", "four"],
["one", "three", "four"],
["two", "three", "four"]]

[...]in all possible lengths 1-4

使用一个范围,用 Enumerable#flat_map 遍历它:

(1..array.length).flat_map {|len| array.combination(len).to_a }

结果:

[["one"],
["two"],
["three"],
["four"],
["one", "two"],
["one", "three"],
["one", "four"],
["two", "three"],
["two", "four"],
["three", "four"],
["one", "two", "three"],
["one", "two", "four"],
["one", "three", "four"],
["two", "three", "four"],
["one", "two", "three", "four"]]

关于ruby-on-rails - 数组的所有变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com