I want to generate 16 random non-negative integers, say a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p.
a+b+c+d = a particular sum
e+f+g+h = another sum
i+j+k+l = another sum
m+n+o+p = another sum
This much is pretty easy. But, the trouble is,
a+e+i+m = another sum
b+f+j+n = another sum
c+g+k+o = another sum
d+h+l+p = another sum
I have written a very elaborate code in Matlab that generates numbers which satisfy the conditions. The code takes around 0.5 seconds and generates around 920 such arrays after running for 1000 iterations. The number 16 is a prototype. The actual number is 1794. So, obviously what I have written isn't gonna be very helpful. Any help would be great!
Thanks.
This problem can be solved as integer program with random weighting cost function, then everytime you run this code, you get a different solution.
A = [A1; -A1; -eye(N)]
b = [sum1; sum2; ...; sumM ; -sum1; -sum2; ... ; -sumM; zeros(N,1)];
intcon = N;
f = randn(N,1); %random cost function, will generate different solution everytime
solution = intlinprog(f,intcon,A,b);
where A1
is a matrix that represent your sums, in your example it will be
A1 = [1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0;
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0;
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0;
1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0;
1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0;
0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0;
0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0;
0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1];
In few words, you transform your constraints to Ax <= b
.
Improved representation:
Aeq = A1
beq = [sum1; sum2; ...; sumM];
ub = inf*ones(N,1);
lb = zeros(N,1);
intcon = N;
f = randn(N,1); %random cost function, will generate different solution everytime
solution = intlinprog(f,intcon,[],[], Aeq, beq, lb, ub);