Ruby | Array permutation() function
Last Updated :
06 Dec, 2019
Array#permutation() : permutation() is a Array class method which returns all permutations of length n of the elements of the array, then return the array itself.
Syntax: Array.permutation()
Parameter: Array
Return: all permutations of length n of the elements of the array, then return the array itself.
Example #1 :
a = [ 18 , 22 , 33 , nil , 5 , 6 ]
b = [ 1 , 4 , 1 , 1 , 88 , 9 ]
c = []
puts "permutation() method form : #{a.permutation(2).to_a}\n\n"
puts "permutation() method form : #{b.permutation(1).to_a}\n\n"
puts "permutation() method form : #{c.permutation(4).to_a}\n\n"
|
Output :
permutation() method form : [[18, 22], [18, 33], [18, nil], [18, 5], [18, 6], [22, 18], [22, 33], [22, nil], [22, 5], [22, 6], [33, 18], [33, 22], [33, nil], [33, 5], [33, 6], [nil, 18], [nil, 22], [nil, 33], [nil, 5], [nil, 6], [5, 18], [5, 22], [5, 33], [5, nil], [5, 6], [6, 18], [6, 22], [6, 33], [6, nil], [6, 5]]
permutation() method form : [[1], [4], [1], [1], [88], [9]]
permutation() method form : []
Example #2 :
a = [ "abc" , "nil" , "dog" ]
c = [ nil ]
b = [ "cow" , nil , "dog" ]
puts "permutation() method form : #{a.permutation(2).to_a}\n\n"
puts "permutation() method form : #{b.permutation(1).to_a}\n\n"
puts "permutation() method form : #{c.permutation(4).to_a}\n\n"
|
Output :
permutation() method form : [["abc", "nil"], ["abc", "dog"], ["nil", "abc"], ["nil", "dog"], ["dog", "abc"], ["dog", "nil"]]
permutation() method form : [["cow"], [nil], ["dog"]]
permutation() method form : []
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...