Skip to content

Commit 5b53866

Browse files
jorgecolladoKevinGilmore
authored andcommitted
[BAEL-1641] Find all pairs of numbers in an array that add up to a given sum (eugenp#3890)
* [BAEL-1641] Find all pairs of numbers in an array that add up to a given sum * Commiting editor's suggested changes * Commiting article Spring Data Reactive Mongo DB microservice in Kotlin * Revert commit for BAEL 1687 - Moving those files to a new branch * Use AssertJ and BDD-style on unit testing
1 parent 5e78d67 commit 5b53866

6 files changed

Lines changed: 278 additions & 0 deletions

File tree

‎algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
77
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
88
import com.baeldung.algorithms.slope_one.SlopeOne;
9+
import com.baeldung.algorithms.pairsaddupnumber.FindPairs;
910

1011
public class RunAlgorithm {
1112

@@ -17,6 +18,7 @@ public static void main(String[] args) throws InstantiationException, IllegalAcc
1718
System.out.println("3 - Simple Genetic Algorithm");
1819
System.out.println("4 - Ant Colony");
1920
System.out.println("5 - Dijkstra");
21+
System.out.println("6 - All pairs in an array that add up to a given sum");
2022
int decision = in.nextInt();
2123
switch (decision) {
2224
case 1:
@@ -37,6 +39,12 @@ public static void main(String[] args) throws InstantiationException, IllegalAcc
3739
case 5:
3840
System.out.println("Please run the DijkstraAlgorithmTest.");
3941
break;
42+
case 6:
43+
final FindPairs findPairs = new FindPairs();
44+
final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3};
45+
final int sum = 6;
46+
findPairs.execute(input, sum);
47+
break;
4048
default:
4149
System.out.println("Unknown option");
4250
break;
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package com.baeldung.algorithms.pairsaddupnumber;
2+
3+
4+
import java.util.ArrayList;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.stream.IntStream;
9+
10+
/**
11+
* Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n)
12+
*/
13+
public class DifferentPairs {
14+
15+
/**
16+
* Show all different pairs using traditional "for" loop
17+
*
18+
* @param input - number's array
19+
* @param sum - given sum
20+
* @return - number's array with all existing pairs. This list will contain just one pair's element because
21+
* the other one can be calculated with SUM - element_1 = element_2
22+
*/
23+
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
24+
final List<Integer> allDifferentPairs = new ArrayList<>();
25+
// Aux. hash map
26+
final Map<Integer, Integer> pairs = new HashMap();
27+
for (int i : input) {
28+
if (pairs.containsKey(i)) {
29+
if (pairs.get(i) != null) {
30+
// Add pair to returned list
31+
allDifferentPairs.add(i);
32+
}
33+
// Mark pair as added to prevent duplicates
34+
pairs.put(sum - i, null);
35+
} else if (!pairs.containsValue(i)) {
36+
// Add pair to aux. hash map
37+
pairs.put(sum - i, i);
38+
}
39+
}
40+
return allDifferentPairs;
41+
}
42+
43+
/**
44+
* Show all different pairs using Java 8 stream API
45+
*
46+
* @param input - number's array
47+
* @param sum - given sum
48+
* @return - number's array with all existing pairs. This list will contain just one pair's element because
49+
* the other one can be calculated with SUM - element_1 = element_2
50+
*/
51+
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
52+
final List<Integer> allDifferentPairs = new ArrayList<>();
53+
// Aux. hash map
54+
final Map<Integer, Integer> pairs = new HashMap();
55+
IntStream.range(0, input.length).forEach(i -> {
56+
if (pairs.containsKey(input[i])) {
57+
if (pairs.get(input[i]) != null) {
58+
// Add pair to returned list
59+
allDifferentPairs.add(input[i]);
60+
}
61+
// Mark pair as added to prevent duplicates
62+
pairs.put(sum - input[i], null);
63+
} else if (!pairs.containsValue(input[i])) {
64+
// Add pair to aux. hash map
65+
pairs.put(sum - input[i], input[i]);
66+
}
67+
}
68+
);
69+
return allDifferentPairs;
70+
}
71+
}
72+
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.algorithms.pairsaddupnumber;
2+
3+
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force"
10+
*/
11+
public class ExistingPairs {
12+
13+
/**
14+
* Show all existing pairs using traditional "for" loop
15+
*
16+
* @param input - number's array
17+
* @param sum - given sum
18+
* @return - number's array with all existing pairs. This list will contain just one pair's element because
19+
* the other one can be calculated with SUM - element_1 = element_2
20+
*/
21+
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
22+
final List<Integer> allExistingPairs = new ArrayList<>();
23+
for (int i = 0; i < input.length; i++) {
24+
for (int j = 0; j < input.length; j++) {
25+
if (j != i && (input[i] + input[j]) == sum) {
26+
allExistingPairs.add(input[i]);
27+
}
28+
}
29+
}
30+
return allExistingPairs;
31+
}
32+
33+
/**
34+
* Show all existing pairs using Java 8 stream API
35+
*
36+
* @param input - number's array
37+
* @param sum - given sum
38+
* @return - number's array with all existing pairs. This list will contain just one pair's element because
39+
* the other one can be calculated with SUM - element_1 = element_2
40+
*/
41+
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
42+
final List<Integer> allExistingPairs = new ArrayList<>();
43+
IntStream.range(0, input.length).forEach(i ->
44+
IntStream.range(0, input.length)
45+
.filter(j -> i != j && input[i] + input[j] == sum)
46+
.forEach(j -> allExistingPairs.add(input[i]))
47+
);
48+
return allExistingPairs;
49+
}
50+
}
51+
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package com.baeldung.algorithms.pairsaddupnumber;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.stream.IntStream;
6+
7+
8+
public class FindPairs {
9+
10+
public void execute(int[] input, int sum) {
11+
final StringBuilder inputArray = new StringBuilder();
12+
inputArray.append("{");
13+
IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", "));
14+
inputArray.append("}");
15+
System.out.println(" Given number array: " + inputArray.toString());
16+
System.out.println(" Given sum: " + sum);
17+
/* Call services */
18+
getDifferentPairs(input, sum);
19+
getExistingPairs(input, sum);
20+
}
21+
22+
/**
23+
* Print all existing pairs for the given inputs: input array & sum number
24+
*/
25+
private static void getExistingPairs(int[] input, int sum) {
26+
List<Integer> pairs = new ArrayList<>();
27+
System.out.println("~ All existing pairs ~");
28+
29+
/* Traditional FOR loop */
30+
// Call method
31+
pairs = ExistingPairs.findPairsWithForLoop(input, sum);
32+
// Create a pretty printing
33+
final StringBuilder output1 = new StringBuilder();
34+
pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, "));
35+
// Print result
36+
System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2));
37+
38+
/* Java 8 stream API */
39+
// Call the method
40+
pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
41+
// Create a pretty printing
42+
final StringBuilder output2 = new StringBuilder();
43+
pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, "));
44+
// Print result
45+
System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2));
46+
}
47+
48+
/**
49+
* Print all different pairs for the given inputs: input array & sum number
50+
*/
51+
private static void getDifferentPairs(int[] input, int sum) {
52+
List<Integer> pairs = new ArrayList<>();
53+
System.out.println("~ All different pairs ~");
54+
55+
/* Traditional FOR loop */
56+
// Call method
57+
pairs = DifferentPairs.findPairsWithForLoop(input, sum);
58+
// Create a pretty printing
59+
final StringBuilder output3 = new StringBuilder();
60+
pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, "));
61+
// Print result
62+
System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2));
63+
64+
/* Java 8 stream API */
65+
// Call method
66+
pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
67+
// Create a pretty printing
68+
final StringBuilder output4 = new StringBuilder();
69+
pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, "));
70+
// Print result
71+
System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2));
72+
}
73+
}
74+
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.algorithms.pairsaddupnumber;
2+
3+
import org.junit.Test;
4+
5+
import java.util.List;
6+
7+
import static org.assertj.core.api.Assertions.assertThat;
8+
import static org.junit.Assert.assertEquals;
9+
import static org.junit.Assert.assertNotNull;
10+
11+
public class DifferentPairsUnitTest {
12+
13+
/* All different pairs */
14+
15+
@Test
16+
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
17+
/* Data */
18+
final int[] input = {2, 4, 3, 3, 8};
19+
final int sum = 6;
20+
/* Call service */
21+
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
22+
/* Check results */
23+
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
24+
}
25+
26+
@Test
27+
public void whenStreamApi_thenReturnAllDifferentPairs() {
28+
/* Data */
29+
final int[] input = {2, 4, 3, 3, 8};
30+
final int sum = 6;
31+
/* Call service */
32+
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
33+
/* Check results */
34+
assertNotNull(pairs);
35+
assertEquals(pairs.size(),2);
36+
assertEquals(pairs.get(0), new Integer(4));
37+
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
38+
}
39+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.algorithms.pairsaddupnumber;
2+
3+
import org.junit.Test;
4+
import java.util.List;
5+
6+
import static org.assertj.core.api.Assertions.assertThat;
7+
8+
9+
public class ExistingPairsUnitTest {
10+
11+
/* All existing pairs */
12+
13+
@Test
14+
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
15+
/* Data */
16+
final int[] input = {2, 4, 3, 3, 8};
17+
final int sum = 6;
18+
/* Call service */
19+
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
20+
/* Check results */
21+
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
22+
}
23+
24+
@Test
25+
public void whenStreamApi_thenReturnAllExistingPairs() {
26+
/* Data */
27+
final int[] input = {2, 4, 3, 3, 8};
28+
final int sum = 6;
29+
/* Call service */
30+
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
31+
/* Check results */
32+
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
33+
}
34+
}

0 commit comments

Comments
 (0)