我正在尝试创建一个数组来显示给定数字输入的每个数字排列。对于给定的输入 "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
函数以仅应用于多维数组中的第二个维度?
假设您已经有一个数组数组,例如
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"]
我是一名优秀的程序员,十分优秀!