Skip to content

Instantly share code, notes, and snippets.

@ChicagoDev
Created March 1, 2023 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChicagoDev/3fb01b4681067b637de9b3d87f8fa2ea to your computer and use it in GitHub Desktop.
Save ChicagoDev/3fb01b4681067b637de9b3d87f8fa2ea to your computer and use it in GitHub Desktop.
public class FindPairs {
public static int countPairs(int[] a) {
Integer[] pairsFound = new Integer[a.length];
// Get the ith item in the list
for (int i = 0; i < a.length; i++) {
// Search for a pair in list from i+1 to N (End of the list)
for (int j=i+1; j<a.length; j++) {
// If array[i] equals any other item to arr[N] True:
if (a[i] == a[j]) {
boolean needToAdd = true;
for (int k=0; k<pairsFound.length; k++) {
if (pairsFound[k] == a[i]) {
needToAdd = false;
}
}
if (needToAdd) {
pairsFound[pairsFound.length-1] = a[i];
}
//Then look in the pairs list. If not in the pairs list -> add it to the paris list
}
}
}
return pairsFound.length;
}
public static void main(String[] args) {
int[] a1 = {1, 3, 1}; // 2 pairs
//int[] a2 = {1, 2, 3, 1, 1, 3}; // 2 pairs
//int[] a3 = {1, 1, 2, 2, 3, 3}; // 3 pairs
System.out.println("An array of size " + a1.length + " has " + countPairs(a1) + " pairs");
//System.out.println("An array of size " + a2.length + " has " + countPairs(a2) + " pairs");
//System.out.println("An array of size " + a3.length + " has " + countPairs(a3) + " pairs");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment