Possible Selections With Repetition.
Imagine being given the opportunity to pick six (6) exercise books
from a book-shop having 10 different brands of exercise books -
Ben 10, Chelsea F.C., Superman, Tottenham F.C.,
Indomitables, Manchester City F.C., Spider Man,
Power Rangers, Liverpool F.C. and Bat Man exercise books.
If you happen to be a big Power Rangers fan, nothing stops you from
selecting all 6 exercise books to be Power Rangers exercise books.
But you can as well decide to pick only 3 Power Rangers exercise books
and make up for the other 3 with any other brands of exercise book.
Code for Repetitive Selection in Java
The algorithm for Selection with Repetition will be a lot similar
to that of combination.
-
Beginning with the first member in the mother set, match it separately with
every member - including itself - until the required Selection group-size (r)
is reached.
-
When every possible Selection with this member is exhausted,
move to the next member in the mother set and repeat Step I.
This is how our Repetitive Selection code in Java will work.
Create a new class file;
Call it Selection
.
Type out the adjoining Java code for Selection with Repetition.
Java code for Selection Class
package miscellaneous;
import java.util.ArrayList;
import java.util.List;
public class Selection {
public String[] words;
public int r;
protected List<String[]> complete_group;
private int i;
public Selection() {
}
public List<String[]> groupSelection(String[] candidates, int size) {
words = candidates;
r = size;
complete_group = new ArrayList<>();
i = 0;
recursiveFillUp(new ArrayList<>());
return complete_group;
}
protected void recursiveFillUp(List<String> temp) {
List<String>[] picked_elements = new List[words.length];
int j = i;
while (j < words.length) {
picked_elements[j] = new ArrayList<>();
picked_elements[j].addAll(temp);
picked_elements[j].add(words[j]);
if (i >= words.length) {
i = j;
}
if (picked_elements[j].size() == r) {
complete_group.add(picked_elements[j].toArray(new String[0]));
} else if (picked_elements[j].size() < r) {
recursiveFillUp(picked_elements[j]);
}
j++;
}
if (picked_elements[--j] != null && picked_elements[j].size() == r) {
i++;
}
}
}
Main Class
package miscellaneous;
import java.util.Arrays;
import java.util.List;
public class Miscellaneous {
public static void main(String[] args) {
String[] goods = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
Selection pick = new Selection();
List<String[]> result = pick.groupSelection(goods, 3);
System.out.println(Arrays.toString(pick.words) + " selection " + pick.r + ":\n");
int i = 0;
for (String[] set : result) {
System.out.println(++i + ": " + Arrays.toString(set) + ";");
}
System.out.println("\nNumber of ways is " + result.size() + ".");
}
}