Added subset generation method and JavaDocs.

This commit is contained in:
Jonathan Turner 2024-02-17 13:39:54 -05:00
parent 75fd07d3e9
commit 6cfc94869b

View File

@ -58,6 +58,36 @@ Algorithm Design Block
*/ */
package Assignments.A2; package Assignments.A2;
import java.util.ArrayList;
import java.util.List;
public class Partition { public class Partition {
private int[] set;
private List<List<Integer>> subsets;
/**
* Generates the list of subsets using Bit Shift Counting by iterating over all combinations of 1 to n.
* After shifting the counter, the current subset is created initialized and if 1 shifted by j is logically
* ANDed with the i is not 0, it adds the value j represents to the subset.
*
* @precondition none
* @postcondition the subsets are generated and added to the field.
*/
public void generateSubsets() {
List<List<Integer>> subsets = new ArrayList<>();
int n = this.set.length;
for (int i = 0; i < (1 << n); i++) {
List<Integer> currentSubset = new ArrayList<>();
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
currentSubset.add(this.set[j]);
}
}
subsets.add(currentSubset);
}
this.subsets = subsets;
}
} }