From da90939e5edc0694533a628eb88129f80ad7e0bf Mon Sep 17 00:00:00 2001 From: Jonathan Turner Date: Sat, 17 Feb 2024 17:42:01 -0500 Subject: [PATCH] Implemented Algorithm Only. --- src/Assignments/A2/Partition.java | 75 ++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/src/Assignments/A2/Partition.java b/src/Assignments/A2/Partition.java index fc173d7..3c005fb 100644 --- a/src/Assignments/A2/Partition.java +++ b/src/Assignments/A2/Partition.java @@ -72,12 +72,85 @@ public class Partition { private int[] set; private List> subsets; + /** + * Iterates through all the possible subsets generated by this.generateSubsets + * and if a subset is found that is exactly half the size it sets the firstset + * to those values and the second subset to the missing values. + * + * @precondition set.length != 0 + * @postcondition the resulting sets are printed. + */ public void performAlgorithm() { - int totalSum = 0; for (int i = 0; i < this.set.length; i++) { totalSum += this.set[i]; } + List firstSubset = null; + List secondSubset = null; + + /* + * Checks through every subset that was generated, + * if a subset is found it sets the firstSubset to the found subset. + */ + for (List subset : subsets) { + int subsetTotal = 0; + for (int value : subset) { + subsetTotal += value; + } + if (totalSum / 2 == subsetTotal) { + firstSubset = subset; + break; + } + } + + /* Checks if a list was found, if so creates second sublist. */ + if (firstSubset != null) { + secondSubset = new ArrayList<>(); + for (int secondValue : this.set) { + if (!firstSubset.contains(secondValue)) { + secondSubset.add(secondValue); + } + } + } + printResults(firstSubset, secondSubset); + } + + /** + * Prints the results of the algorithm based on the two subsets. Prints the setsize, the original set. + * If the subsets were null (No match found) print output associated, else print the both lists. + * + * @precondition none + * @postcondition the output is displayed. + * + * @param firstSubset the first subset. + * @param secondSubset the second subset. + */ + private void printResults(List firstSubset, List secondSubset) { + int setSize = this.set.length; + String original = ""; + for (int values : this.set) { + original += values + " "; + } + String first = "{"; + String second = "{"; + if (firstSubset != null) { + for (int fvalues : firstSubset) { + first += fvalues + ","; + } + first = first.substring(0, first.length()-1) + "}"; + for (int svalues : secondSubset) { + second += svalues + ","; + } + second = second.substring(0, second.length()-1) + "}"; + } else { + first = "No disjoint subsets with the same sum"; + second = "of their elements found"; + } + + System.out.println("Set size: " + setSize); + System.out.println("Integer values: " + original); + System.out.println("Disjoint subsets with same sum: " + first); + System.out.println(" " + second); } /**