Question

I am trying to create an array that shows every digit permutation of a given number input. With a given input "123", the array should look like this:

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

I can get an array containing arrays of the separate digits:

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"]]

but I cannot figure out how to join the second or third dimensions of arraycombinations while preserving the first dimension.

Each of these attempts failed:

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

How can I isolate the join function to apply to only the second dimension within a multidimensional array?

Was it helpful?

Solution 2

It's simple really

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

Let me explain a bit:

"123".split("") gives you an array ["1","2","3"] permutation.to_a gives you array of arrays [["1","2","3"], ["2","1","3"] ... ] then you must join each of those arrays inside with map { |x| x.join } and you get the required end result.

OTHER TIPS

Assuming you already have an array of arrays such as

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"]

Like this:

arraycombinations.map(&:join)
# => ["123", "132", "213", "231", "312", "321"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top