0

I have to do some very repetitive calculations based on how many objects there are.

Example there are 4 objects.

Then I have to do these calculations:

1+2
1+3
1+4

2+1
2+3
2+4

3+1
3+2
3+4

4+1
4+2
4+3

1+3+2
1+4+3
1+2+4

3+2+1
3+4+2
3+2+4

4+2+1
4+3+1
4+2+3

1+2+3+4

How to do this in a non repetitive way of calculation all possibilities ? I want to calculate all possibilities expect that a object my not appear twice.

2 Answers 2

2
objs = [1, 2, 3, 4]
(1..objs.size).map {|i| objs.permutation(i).map {|o| o.reduce(:+) } }.flatten(1)
# => [
1, # 1
2, # 2
3, # 3
4, # 4
3, # 1+2
4, # 1+3
5, # 1+4
3, # 2+1
5, # 2+3
6, # 2+4
...
10, # 1+2+3+4
...
10 # 4+3+2+1
]
Sign up to request clarification or add additional context in comments.

3 Comments

some details: the addition is a commutative operation, so you can simply do a objs.combination(i) instead of a permutation. And map + flatten(1) -> flat_map (ruby 1.9). 2.upto(xs.size).flat_map { |n| xs.combination(n).map { |cs| cs.inject(:+) } }
@tokland how to do a combination? :)
Does it matter if a use example [14, 25] instead [1, 2]?
1

You can look at Array.permutations

When invoked with a block, yield all permutations of length n of the elements of ary, then return the array itself. If n is not specified, yield all permutations of all elements. The implementation makes no guarantees about the order in which the permutations are yielded.

1 Comment

Please include an excerpt or explanation. "Bare links" are better as 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.