フィルターのクリア

I am having an array with positive integers, and i want to know all the possibility that the sum of elements of the array is close to or equal to a number say (N))

2 ビュー (過去 30 日間)
I am having an array with positive integers, and i want to know all the possibility that the sum of elements of the array is close to or equal to a number say (N)) and no index (element in the array) will be repeated
A = [ 0 7 30 16 23 11 19 15 28 8 8 7 14 6 19 11 12 26 17 6 15 5 10 ]
N = 40 (or close to 40 like 36,37,38,39)
the possible sum of the numbers are like
8+6+26 = 40
23+15 = 38
16+17+6=39
15+5+19=39
and so on
  4 件のコメント
Matt J
Matt J 2023 年 1 月 5 日
編集済み: Matt J 2023 年 1 月 5 日
Why is 23+15 = 38 an acceptable selection when it is still possible to add further A(i) to the sequence without exceeding N=40? In particular: 23+15+0 = 38

サインインしてコメントする。

採用された回答

Matt J
Matt J 2023 年 1 月 5 日
編集済み: Matt J 2023 年 1 月 6 日
N=40;
A = [1 7 13 20 38 39 40];
A=unique(A);
n=find(cumsum(A)<=N,1,'last');
result=cell(n,1);
for i=1:n
tmp=subCollection(N,A,i);
tmp(:,end+1:n)=nan;
result{i}=tmp;
end
result=cell2mat(result) %final result
result = 7×3
40 NaN NaN 1 38 NaN 1 39 NaN 1 7 13 1 7 20 1 13 20 7 13 20
function T=subCollection(N,A,m)
J=nchoosek(1:numel(A),m);
I=repmat( (1:height(J))' ,1,m);
%S=sparse(I,J,1);
S=accumarray([I(:),J(:)],1);
delta=N-S*A(:);
C=(1./(1-S));
mincomp=min( C.*A(:).' ,[],2);
idx=delta<mincomp & delta>=0;
T=(1./S).*A(:).';
T=sort(T(idx,:),2);
T(isinf(T))=nan;
T=T(:,1:m);
end
  2 件のコメント
Ashish Verma
Ashish Verma 2023 年 1 月 7 日
According to me results will be some matrices, where the sum will be close to 40 and the matrix contains distinct elements or no index of array will be repeated (because of duplicacy). For eg, possibility of 3 elements sum will be
[8+6+26 = 40
23+15 = 38
16+17+6=39
15+5+19=39
...]
Matt J
Matt J 2023 年 1 月 7 日
That is what I have given you.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by