I want the combinations method to be modified if it is possible without using <S
ID: 3536996 • Letter: I
Question
I want the combinations method to be modified if it is possible without using <Set>
import java.util.*;
public class Combinations {
/*
* Recursive method to return a set of all combinations of size k from a group
*/
public static Set<Set<Integer>> combinations(List<Integer> group, int k) {
Set<Set<Integer>> allCombos = new HashSet<Set<Integer>> ();
// base cases for recursion
if (k == 0) {
// There is only one combination of size 0, the empty team.
allCombos.add(new HashSet<Integer>());
return allCombos;
}
if (k > group.size()) {
// There can be no teams with size larger than the group size,
// so return allCombos without putting any teams in it.
return allCombos;
}
// Create a copy of the group with one item removed.
List<Integer> groupWithoutX = new ArrayList<Integer> (group);
Integer x = groupWithoutX.remove(groupWithoutX.size()-1);
Set<Set<Integer>> combosWithoutX = combinations(groupWithoutX, k);
Set<Set<Integer>> combosWithX = combinations(groupWithoutX, k-1);
for (Set<Integer> combo : combosWithX) {
combo.add(x);
}
allCombos.addAll(combosWithoutX);
allCombos.addAll(combosWithX);
return allCombos;
}
public static void showteams(int n, int k) {
List<Integer> group = new ArrayList<Integer>();
for (int i=0; i<n; i++) {
group.add(i);
}
for (Set<Integer> team : combinations(group,k)) {
for (Integer member : team) {
System.out.print(member+" ");
}
System.out.print(" ");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter group size: ");
int n = in.nextInt();
in.nextLine();
System.out.print("Enter team size: ");
int k = in.nextInt();
in.nextLine();
System.out.println("Here are all possible teams.");
showteams(n,k);
}
}
Explanation / Answer
import java.util.*; public class Combinations { /* * Recursive method to return a set of all combinations of size k from a group */ public static Set combinations(List group, int k) { Set allCombos = new HashSet (); // base cases for recursion if (k == 0) { // There is only one combination of size 0, the empty team. allCombos.add(new HashSet()); return allCombos; } if (k > group.size()) { // There can be no teams with size larger than the group size, // so return allCombos without putting any teams in it. return allCombos; } // Create a copy of the group with one item removed. List groupWithoutX = new ArrayList (group); Integer x = groupWithoutX.remove(groupWithoutX.size()-1); Set combosWithoutX = combinations(groupWithoutX, k); Set combosWithX = combinations(groupWithoutX, k-1); for (Set combo : combosWithX) { combo.add(x); } allCombos.addAll(combosWithoutX); allCombos.addAll(combosWithX); return allCombos; } public static void showteams(int n, int k) { List group = new ArrayList(); for (int i=0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.