user1014888
user1014888

Reputation: 431

Creating pairs from an Array?

Is there a simple way to create pairs from an array?

For example, if I have an array [1,2,3,4] how would I go about trying to return this array?

[[1,2], [1,3], [1,4], [2,1], [2,3], [2,4], [3,1], [3,2], [3,4], [4,1], [4,2], [4,3]] 

Every element is paired with every other other element except itself, and duplicates are allowed.

Upvotes: 1

Views: 1120

Answers (2)

Krule
Krule

Reputation: 6476

[1,2,3,4].permutation(2).map{ |n| "(#{ n.join(",") })" }
# => ["(1,2)", "(1,3)", "(1,4)", "(2,1)", "(2,3)", "(2,4)", "(3,1)", "(3,2)", "(3,4)", "(4,1)", "(4,2)", "(4,3)"] 

Upvotes: 2

BaronVonBraun
BaronVonBraun

Reputation: 4293

You can use Array#permutation for this:

[1,2,3,4].permutation(2).to_a
# => [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]

Upvotes: 4

Related Questions