jeudi 27 mai 2010

Get all combinations of 3 elements of an array of ints and print those that sum to 0

// input an array of ints [1, 2, 3, 4, 5, -6]
// print = output all 3-tuples that sum to zero (1, 5, -6) (2, 4, -6)


FIRST WE ASSUME that ints are all DIFFERENT
combi(n,s):

for i = 0 ; i < n ; i++
for j = i+1 ; j < n ; j++
for k = j+1 ; k < n ; k++
if s[i]+s[j]+s[k] == 0
print i,j,k



SECOND WE ASSUME THat the ints are SORTED

for i = 0 ; i < n ; i++
for j = i+1 ; j < n ; j++
for k = j+1 ; k < n ; k++
if s[i]+s[j]+s[k] == 0:
print i,j,k
elif s[i]+s[j]+s[k] > 0:
break

Aucun commentaire:

Enregistrer un commentaire