Just learning and hoping to change careers...I need help correcting the 2nd and 3rd methods so they print correctly! I was able to hack this together(which took a very long time), what code do I need to fix the 2nd and 3rd methods?
I'd like to get it working and then go back and teach myself as that's my learning style!
Both the 2nd and 3rd methods are incorrectly printing these pairs: (5,5)(5,5)(6,4)(9,1)
import java.util.*;
public class TenPairs {
public static void main(String[] args) {
int a[] = { 1, 1, 2, 4, 4, 5, 5, 5, 6, 7, 9 };
findAllPairs(a, 10);
findUniquePairs(a, 10);
findComboPairs(a, 10);
}
// Method 1 - output all pairs would output: [1,9], [1,9], [4,6], [4,6], [5,5],
// [5,5], [5,5], [5,5], [5,5],[5,5],[6,4],[6,4][9,1],[9,1]
static void findAllPairs(int[] array, int sum) {
System.out.println("All pairs(including duplicates and reverse order pairs) whose sum is " + sum + ":");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
System.out.println("(" + array[i] + "," + array[j] + ")" + "(" + array[j] + "," + array[i] + ")");
}
}
}
}
// Method2 - output unique pairs only once would output: [1,9], [4,6], [5,5],
// [6,4], [9,1]
static void findUniquePairs(int[] array, int sum) {
System.out.println("All pairs only once(including reverse order pairs but excluding duplicates) whose sum is "
+ sum + ":");
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
if (pairs.containsKey(sum - array[i]))
System.out.println("(" + array[i] + "," + (sum - array[i]) + ")");
else
pairs.put(array[i], 0);
}
}
// Method3 - output the same combo pair only once would output: [1,9], [4,6],
// [5,5]
static void findComboPairs(int[] array, int sum) {
System.out
.println("All pairs only once(excluding reverse order pairs and duplicates) whose sum is " + sum + ":");
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
if (pairs.containsKey(sum - array[i]))
System.out.println("(" + array[i] + "," + (sum - array[i]) + ")");
else
pairs.put(array[i], 0);
}
}
}