How to add any number of variables together in all combinations?
Show older comments
I am trying to solve the three sum problem. It states that when provided a vector of a given length, three of the numbers in the vector add to zero. I am tasked with finding any and all of the combinations of numbers that add to zero.
For example, if the vector input is [3 1 3 -4 -6], the answers the code should output are: [3 1 -4], [3 1 -4] (repeated because two 3s are given) and [3 3 -6].
As of right now, I have code that assigns a variable to each of the numbers in the matrix:
---------------------------------
F = [3 1 3 -4 -6 ]; H = size(F); G = H(1,2);
for n = 1:G eval(['k' num2str(n) '= F(n)']) end
---------------------------------
What I need to do now is find out how to sum every combination of three of the numbers. If anyone could help me with this I'd be very grateful! Thank you for your time!
Answers (2)
You can use NCHOOSEK. You should avoid using EVAL actually, which is quite slow, and rarely appropriate. Also, look at the doc of SUM and see how you can specify the dimension along which it has to perform the summation; this should be useful to you.
2 Comments
Mark Schillinger
on 25 Apr 2013
Can you use RANDPERM or PERMS?
If not, there would be a not-that-simple solution based on BSXFUN I guess, but if the statement of your HW disallows this kind of functions, you might end up implementing a triple FOR loop, or a double FOR and and a FIND.
If you end up implementing a solution based on loops, "think on paper" and once you have an algorithm implement it (don't start thinking "what command should I type).
The triple FOR loop, for example, would be based on an approach where you sum up elements 1, 2, 3 of F (whose values are 3, 1, 3) in a first step and check whether the sum is null, then you sum up elements 1,2,4 and perform the same test, then 1,2,5, etc.
On this note, I'm off for the night!
Jan
on 25 Apr 2013
1 vote
Did you search in the FileExchange already?
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!