2

In my function I have to find all unique triplets to given numbers K from given array. It finds all triplets but many of them are there twice or more like 1 1 5 is same as 1 5 1 or 5 1 1 and etc.

Can somebody help me with this?

int triplet(int *array, int size, int K) {
  int i, j, k;
  int found = 0; /* triplets whose sum is equal to K */
  for(i = 0; i < size; i++) {
    for (j = 0; j < size; j++) {    
      for (k = 0; k < size; k++) {
        if(array[i] + array[j] + array[k] == K) {
          printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
          found++;
        }           
      }
    }
  }
  return found;
}
Bojan B
  • 2,091
  • 4
  • 18
  • 26
blackroad
  • 29
  • 1
  • 5

2 Answers2

0

To exclude combinations you could try the following change:

int triplet(int *array, int size, int K) {
  int i, j, k;
  int found = 0; /* triplets whose sum is equal to K */
  for(i = 0; i < size; i++) {
    for (j = i; j < size; j++) {    
      for (k = j; k < size; k++) {
        if(array[i] + array[j] + array[k] == K) {
          printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
          found++;
        }           
      }
    }
  }
  return found;
}

Notice the j = i and k = j statements in the for loop declarations. This way you will skip the possible duplicates for your case and yet cover all variations of the i, j and k variables.

Bojan B
  • 2,091
  • 4
  • 18
  • 26
0

You should not repeat already processed combinations; a possible solution would be to start each for cycle from de previous ID + 1, like so:

for(i = 0; i < size; i++) {
 for (j = i+1; j < size; j++) {    
  for (k = j+1; k < size; k++) {
    if(array[i] + array[j] + array[k] == K) {
      printf("Triplet Found : %d, %d, %d\n", array[i], array[j], array[k]);
      found++;
    }           
  }
}

setting j = i + 1; you prevent same-element triplets!

Giovazz89
  • 391
  • 3
  • 12