Ruby | Array combination() operation

Array#combination() : combination() is an Array class method which invokes with a block yielding all combinations of length ‘n’ of elements of the array.

Syntax:  Array.combination()

Parameter:  Arrays in which we want elements to be invoked

Return:  all combinations of length 'n' of elements of the array.

Code #1 : Example for combination() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for combination() method
  
# declaring array
a = [1, 2, 56, 23]
  
# combination of length 2
puts "combination a : #{a.combination(2).to_a}\n\n"
  
# combination of length 3
puts "combination a : #{a.combination(3).to_a}\n\n"

chevron_right


Output :

combination a : [[1, 2], [1, 56], [1, 23], [2, 56], [2, 23], [56, 23]]

combination a : [[1, 2, 56], [1, 2, 23], [1, 56, 23], [2, 56, 23]]

Code #2 : Example for combination() method

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for combination() method
  
# declaring array
a = [[1, 2, 56, 23],
    [34, 54, 23, 1]]
  
# combination of length 2
puts "collect a : #{a.combination(2).to_a}\n\n"
  
# combination of length 1
puts "collect a : #{a.combination(1).to_a}\n\n"

chevron_right


Output :

collect a : [[[1, 2, 56, 23], [34, 54, 23, 1]]]

collect a : [[[1, 2, 56, 23]], [[34, 54, 23, 1]]]

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : timcustard