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 Perl
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 Perl will work.
Create a new module file;
Call it Selection.pm
.
Type out the adjoining Perl code for Selection with Repetition.
Perl code for Selection.pm Module
package SELECTION;
BEGIN {
require Exporter;
our $VERSION = 2017.10;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(possibleWordCombinations);
}
use warnings;
use strict;
our @words;
our $r;
my $i;
my @complete_group;
sub new {
my $self = shift;
my $this = {};
bless $this, $self;
return $this;
}
sub groupSelection {
shift;
my $arg = shift;
@words = @{$arg};
$r = shift;
@complete_group = ();
$i = 0;
recursiveFillUp([]);
return \@complete_group;
}
sub recursiveFillUp {
my $temp = shift;
my @picked_elements = ();
my $j = $i;
while ($j < scalar @words) {
$picked_elements[$j] = [@{$temp}];
push @{$picked_elements[$j]}, $words[$j];
$i = $j if $i >= scalar @words;
if (scalar @{$picked_elements[$j]} == $r) {
push @complete_group, $picked_elements[$j];
} elsif (scalar @{$picked_elements[$j]} < $r) {
recursiveFillUp($picked_elements[$j]);
}
$j++;
}
if (defined $picked_elements[--$j] && scalar @{$picked_elements[$j]} == $r) {
$i++;
}
}
1;
Main Class
use strict;
use warnings;
use SELECTION;
my @subjects = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
my $r = 9;
my $pick = SELECTION->new();
my $result = $pick->groupSelection(\@subjects, $r);
print ("[", join(", ", @subjects), "] selection ", $r, ":\n\n");
my $i = 0;
print (++$i, ": ", join(", ", @{$_}), "\n") for @{$result};
print ("\n\nNumber of ways is ", scalar @{$result}, ".");
print "\n\n";