Implemented Algorithm Only.

This commit is contained in:
Jonathan Turner 2024-02-17 17:42:01 -05:00
parent 7fa5f88499
commit da90939e5e

View File

@ -72,12 +72,85 @@ public class Partition {
private int[] set;
private List<List<Integer>> 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<Integer> firstSubset = null;
List<Integer> secondSubset = null;
/*
* Checks through every subset that was generated,
* if a subset is found it sets the firstSubset to the found subset.
*/
for (List<Integer> 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<Integer> firstSubset, List<Integer> 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);
}
/**