Home > database >  Finding total number of triplets that sum upto a certain value in C getting incorrect output?
Finding total number of triplets that sum upto a certain value in C getting incorrect output?

Time:01-29

Here is my code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    system("cls");
    int count = 0;
    int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };

    for (int i = 0; i < 8; i  ) {
        for (int j = 0; j < 8; j  ) {
            for (int k = 0; k < 8; k  ) {
                if (arr[i]   arr[j]   arr[k] == 12 && arr[i] != arr[j] && arr[j] != arr[k]) {
                    count = count   1;
                }
            }
        }
    }
    printf("Count=%d", count);
    return 0;
}

My expected output is 6. But I'm getting 36 as output.

When I change j = i 1, and k = j 1, the code works. But I'm not sure why it works. Mine code should also work as I've tested all possible conditions.

I understand why my code doesn't work it's because it produces below output:

1 3 8
1 4 7
1 5 6
1 6 5
1 7 4
1 8 3
2 3 7
2 4 6
2 6 4
2 7 3
3 1 8
3 2 7
3 4 5
3 5 4
3 7 2
3 8 1
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
5 1 6
5 3 4
5 4 3
5 6 1
6 1 5
6 2 4
6 4 2
6 5 1
7 1 4
7 2 3
7 3 2
7 4 1
8 1 3
8 3 1

CodePudding user response:

At the end of the long if statement you have

arr[i] != arr[j] != arr[k]

I guess you are trying to compare all 3 variables but that's not what the code does. Besides that you have already made that check with arr[i] != arr[j] && arr[j] != arr[k] && arr[i] != arr[k] so you don't need it.

That said, I find it strange that you check the values for being equal. I would expect that you should check the index, i.e. like i != j && i != k && j != k.

Anyway your code is also wrong because you start all three loops from zero. Starting all loops from zero causes the code to check the same triplet several times, i.e.

i  j  k
-------
1  2  3   will be checked
1  3  2   will be checked
2  1  3   will be checked
2  3  1   will be checked
3  1  2   will be checked
3  2  1   will be checked

So you check the same triplet 6 times. That's not what you want (I assume).

Instead consider:

#include <stdio.h>
#include <stdlib.h>
int main()
{
  system("cls");
  int count = 0;
  int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8};
 
  for (int i = 0; i < 8; i  )
  {
    for (int j = i 1; j < 8; j  )
    {
      for (int k = j 1; k < 8; k  )
      {
        if (arr[i]   arr[j]   arr[k] == 12)
        {
          count = count   1;
        }
      }
    }
  }
  printf("Count=%d", count);
  return 0;
}
  •  Tags:  
  • c
  • Related