1

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.

1
  • What you describe is not an array, not even a valid Ruby code. Commented Jan 16, 2013 at 17:46

2 Answers 2

4

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

How can I access one of the elements in each of the pair, for example say I want to increment the second value in each pair by 1. e.g. [1,3],[1,4].....
2
[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)"] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.