Vish
Vish

Reputation: 319

How to find all combinations of a given set of numbers

I came across a problem where say I have a set of numbers (1,2). How do I get all possible combinations of the positive and negatives in the set. My result set should be 1,2 -1,2 1,-2 -1,-2

I started off suming the numbers and putting a coefficient in front of each of them. If your numbers are A1..AN, you add N coefficients (C1..CN) and sum. In this case the coeeficients would be 1 amd -1. Similar to solving a multivalued polynomial I guess.

How do I get all possible combinations though ? ANy help is much appreciated.

Upvotes: 0

Views: 279

Answers (1)

Bill
Bill

Reputation: 3977

Try this

set={1,2};
Tuples[Transpose[{set,-1*set}]]

which gives you

{{1,2},{1,-2},{-1,2},{-1,-2}}

And that will work with sets containing any (reasonable) number of elements, even including symbols.

Upvotes: 2

Related Questions