-
Notifications
You must be signed in to change notification settings - Fork 4
/
Triplet sum.cpp
62 lines (54 loc) · 1.43 KB
/
Triplet sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
PROBLEM:
Given a random integer array and a number x. Find and print the triplets of elements in the array which sum to x.
While printing a triplet, print the smallest element first.
That is, if a valid triplet is (6, 5, 10) print "5 6 10". There is no constraint that out of 5 triplets which have to be printed on 1st line. You can print triplets in any order, just be careful about the order of elements in a triplet.
Input format :
Line 1 : Integer N (Array Size)
Line 2 : Array elements (separated by space)
Line 3 : Integer x
Output format :
Line 1 : Triplet 1 elements (separated by space)
Line 2 : Triplet 3 elements (separated by space)
Line 3 : and so on
Constraints :
1 <= N <= 1000
1 <= x <= 100
Sample Input:
7
1 2 3 4 5 6 7
12
Sample Output ;
1 4 7
1 5 6
2 3 7
2 4 6
3 4 5
CODE:
*/
void FindTriplet(int arr[], int size, int x) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Print output and don't return it.
* Taking input is handled automatically.
*/
for(int i = 0;i<size;i++){
for(int j = i;j<size;j++){
if(arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i = 0;i<size;i++){
for(int j = i;j<size;j++){
for(int k = j;k<size;k++){
if(arr[i]+arr[j]+arr[k]==x && (i!=j && j!=k && i!=k)){
cout<<arr[i]<<" "<<arr[j]<<" "<<arr[k]<<endl;
}
}
}
}
return;
}