How to fast determine all possible solutions for such a+b+c+d+...+n=x?

6 views (last 30 days)

I have values which are in four seperate vectors such as:

toplam1 % 1x1000 double

toplam2 % 1x1000 double

toplam3 % 1x1000 double

toplam4 % 1x1000 double

I need to find the highest sum value of toplam(a) + toplam(b) + toplam(c) + toplam(d) for a + b + c + d = 1000 condition. For instance the solution might be like this: toplam1(120) + toplam2(80) + toplam3(500) + toplam4(300) where 120+80+500+300=1000.

First of all I've tried to determine the all possible solutions of a+b+c+d=1000 equation:

cond = 1000;
%preallocation for faster solution
preAll = (cond-10)^3; %3 nested loops
kayit1 = zeros(1, preAll);
kayit2 = zeros(1, preAll);
kayit3 = zeros(1, preAll);
kayit4 = zeros(1, preAll);
a=1; b=1; c=1; m=1;
for i=1:cond
    for ii=1:cond
        for iii=1:cond
            d = 1000-a-b-c;
            kayit1(m) = a;
            kayit2(m) = b;
            kayit3(m) = c;
            kayit4(m) = d;
            c=c+1;
            m=m+1;
        end
        b=b+1;
        c=1;
    end
    a=a+1;
    b=1;
    c=1;
end

My main problem is, this code takes too much time to evaulate and when it is done it gaves 970 billions values which need to be examined. To find the highest sum I have used this code:

vals= zeros(1,preAll);
m=1;
for i=1:preAll
    vals(m) = toplam1(kayit1(m))+toplam2(kayit2(m))+toplam3(kayit3(m))+toplam4(kayit4(m));
    m=m+1;
    i=i+1;
end
[val1, index1] = max(vals);
%After finding the index1, I should be able to determine a,b,c and d.

This code gives "subscript indices must either be real positive integers or logicals." error because of exceeding integer value of i I guess.

So, is there better/faster solution for such equations like a+b+c+d+...+n=x or another approach to find highest sum?

Answers (2)

Image Analyst
Image Analyst on 22 Aug 2018
Put in "break"s to bail out of a loop once the sum gets past 1000. No sense in computing, like, 500+600+400+800, when the sum exceeded 1000 long long ago.

Walter Roberson
Walter Roberson on 22 Aug 2018
Edited: Walter Roberson on 22 Aug 2018
for i=1:cond-3
for ii=1:cond-i-2
for iii=1:cond-i-ii-1
d = 1000-a-b-c;
kayit1(m) = a;
kayit2(m) = b;
kayit3(m) = c;
kayit4(m) = d;
c=c+1;
m=m+1;
end
b=b+1;
c=1;
end
a=a+1;
b=1;
c=1;
end
This takes a small number of seconds on my system.
This uses 165668499 out of 970299000 reserved entries, which is about 17.1 percent used. You could reduce the memory allocation of your variables.

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!