0

here is the problem

I have an array:

a = [1, 2, 3, 4]

and want to get:

b = [[1, 2, 3], [1, 3, 4], [1, 2, 4], [2, 3, 4]]

what is the best way? thanks!

4
  • 1
    Looks to me like you're already done! Commented Mar 12, 2012 at 20:06
  • what about [1, 2, 3, 4, 5, 6, 7, 8] Commented Mar 12, 2012 at 20:07
  • Are you asking someone to do your homework for you? Commented Mar 12, 2012 at 20:10
  • 1
    what have you tried? and what would be the expected output there? do you want all 7 element groups? all 3 element groups? Ask the question better and you'll get answers better than my snark. Commented Mar 12, 2012 at 20:10

2 Answers 2

3

You are looking for all unique sets of 3 elements out of a set of 4.

Use Array#combination method:

a = [1, 2, 3, 4]
b = a.combination(3).to_a

output:

=> [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

More info:

Array#combination
Wikipedia Combination

Sign up to request clarification or add additional context in comments.

Comments

0

Here would be my first implementation. (But performance suckz i guess)

array = [1,2,­3,4]
b = []
array.each­{|e| c = array­.clone; c.del­ete(e); b << c}
# b.sort!

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.