如何在不影响第一维的情况下连接第二维或第三维数组项

时间:2014-04-03 08:50:10

标签: ruby arrays join multidimensional-array permutation

我正在尝试创建一个数组,显示给定数字输入的每个数字排列。使用给定的输入"123",数组应如下所示:

["123", "132", "213", "231", "312", "321"]

我可以得到一个包含不同数字数组的数组:

a = []
"123".split('').each {|n| a.push(n) }
arraycombinations = a.permutation(a.length).to_a
# => [["1", "2", "3"], ["1", "3", "2"], ["2", "1", "3"], ["2", "3", "1"], ["3", "1", "2"], ["3", "2", "1"]]

但我无法弄清楚如何在保留第一维的同时加入arraycombinations的第二维或第三维。

这些尝试都失败了:

arraycombinations.map {|x| print arraycombinations.join("") }
arraycombinations.map {|ar| ar.split(",") }
arraycombinations.each {|index| arraycombinations(index).join("") }

如何隔离join函数以仅应用于多维数组中的第二维?

3 个答案:

答案 0 :(得分:3)

假设您已经拥有一组数组,例如

a = [["1","2","3"],["1","3","2"],["2","1","3"],["2","3","1"], ["3","1","2"],["3","2","1"]]

a.map { |i| i.join}
#=>["123", "132", "213", "231", "312", "321"]

答案 1 :(得分:2)

这很简单

"123".split("").permutation.to_a.map { |x| x.join }

让我解释一下:

"123".split("")为您提供一个数组["1","2","3"] permutation.to_a,为您提供数组数组[["1","2","3"], ["2","1","3"] ... ] 然后你必须加入map { |x| x.join }里面的每个数组 并得到所需的最终结果。

答案 2 :(得分:2)

像这样:

arraycombinations.map(&:join)
# => ["123", "132", "213", "231", "312", "321"]