java - Find array elements equal to a given sum -


suppose array is: [1, 2, 5, 7, 10, 13, 17, 21] , have find 5 numbers sum equal 31. algorithm?

for small array such have, efficiency doesn't mean much. trick make fast. work (written in matlab, translate language easily):

array=[1, 2, 5, 7, 10, 13, 17, 21]; sum_val=31;  a=1:(length(array)-4] b=(a+1):(length(array)-3) c=(b+1):(length(array)-2) d=(c+1):(length(array)-1) e=(d+1):(length(array)-0) if array(a)+array(b)+array(c)+array(d)+array(e)=sum_val fprintf("%i+%i+%i+%i+%i=%i",array(a),array(b),array(c),array(d),array(e),sum_val); end end end end end 

Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -