Skip to content

Commit ef8f39a

Browse files
authored
Merge pull request #80 from arpitjain22june/patch-12
Create SumTriplet.java
2 parents 1220bc2 + 30ec663 commit ef8f39a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
Take as input N, the size of array. Take N more inputs and store that in an array. Take as input “target”, a number. Write a function which prints all triplets of numbers which sum to target.
2+
3+
Input Format
4+
First line contains input N.
5+
Next line contains N space separated integers denoting the elements of the array.
6+
The third line contains a single integer T denoting the target element.
7+
8+
Constraints
9+
Length of Array should be between 1 and 1000.
10+
11+
Output Format
12+
Print all the triplet present in the array in a new line each. The triplets must be printed as A, B and C where A,B and C are the elements of the triplet ( A<=B<=C) and all triplets must be printed in sorted order. Print only unique triplets.
13+
14+
Sample Input
15+
9
16+
5 7 9 1 2 4 6 8 3
17+
10
18+
Sample Output
19+
1, 2 and 7
20+
1, 3 and 6
21+
1, 4 and 5
22+
2, 3 and 5
23+
Explanation
24+
Array = {5, 7, 9, 1, 2, 4, 6 ,8 ,3}. Target number = 10. Find any three number in the given array which sum to target number.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.Arrays;
2+
import java.util.Scanner;
3+
4+
public class SumTriplet {
5+
//find triplet with sum =x
6+
public static void main(String[] args) {
7+
Scanner sc = new Scanner(System.in);
8+
int n = 0;
9+
if (sc.hasNext()) {
10+
n = sc.nextInt();
11+
}
12+
13+
int[] a = new int[n];
14+
for (int i = 0; i < n; i++) {
15+
a[i] = sc.nextInt();
16+
}
17+
Arrays.sort(a);
18+
int x = sc.nextInt();
19+
for (int i = 0; i < n - 2; i++) {//loop for a fix number and rest like sum pair
20+
int l = i + 1;
21+
int h = n - 1;
22+
while (l < h) {
23+
int s = a[i] + a[l] + a[h];
24+
if (s == x) {
25+
System.out.println(a[i] + ", " + a[l] + " and " + a[h]);
26+
l++;
27+
h--;
28+
} else if (s > x) {
29+
h--;
30+
} else {
31+
l++;
32+
}
33+
}
34+
35+
}
36+
}
37+
38+
}

0 commit comments

Comments
 (0)