usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Code for Combination (Selection Without Repetition) in Perl



Code for Doing Combination in Perl

Writing up an algorithm to carry out the different Combination - Selection without Repetition, nCr - of a set of things in Perl requires some level of imaginative thinking.

Get a writing pad and pencil:
  1. Write out all n members in the set - for Combination - at the top of the pad.
  2. Beginning with the first member, match it separately with the other members until the required selected-group size (r) is reached.
  3. When every possible Combination for this first member is exhausted, remove the current first member from the mother set.
    The immediate next member becomes the new first member in the culminating set.
  4. Take the first member in what is left of the mother set and repeat the same process from step II.

How to carry out combination

This is exactly what we will do with code to list up all possible selections without repetition in Perl.

Create a new Perl Class File; call it Miscellaneous.pl.
Create a new Perl Module File; call it Combination.pm.

Type out the adjoining Perl code for the combination of different options (nCr).



Why Bother About Combination

Well, isn't it obvious?
Say you are to pick only four (4) pupils from a class of six - such a small class; our little Combination algorithm solves this little problem for you by showing all your possible options / selection outcomes.








Perl Code for Combination.pm Module

package COMBINATION;

BEGIN {
    require Exporter;

    # for the sake of standard
    our $VERSION = 2017.10;

    # Inherit from exporter to export functions and variables
    our @ISA = qw(Exporter);

    # Functions and variables to be exported by default
    our @EXPORT_OK = qw(possibleWordCombinations);
}

use warnings;
use strict;

my @words;
my $r# min length of word
my @comb_store# array of references
my $i;

# simulate an object construct
sub new {
    my $self = shift;
    
    my $this = {};
    bless $this$self;
    
    return $this;
}

# point of entry
# returns an array reference of references to array strings
sub possibleWordCombinations {
    shift;
    my $arg = shift;
    @words = @{$arg};
    $r = shift;
    @comb_store = ();
    $i = 0;
    # check for conformity
    if ($r <= 0 || $r > scalar @words) {
        @comb_store = ();
    } elsif ($r == 1) {
        $comb_store[$_] = [$words[$_]] for (0 .. $#words);
    } else {
        progressiveCombination();
    }
    return \@comb_store;
}

# do combinations for all 'words' element
sub progressiveCombination {
    # anonymous reference to a single element array as 1st argument
    repetitivePairing([$words[$i]], $i + 1);
    if ($i + $r <= scalar @words) {
        # move on to next degree
        $i++;
        progressiveCombination();
    }
}

# do all possible combinations for 1st element of this array
sub repetitivePairing {
    my $prefix_word = shift# array reference
    my $position = shift# int
    my @auxiliary_store = ();
    for (0 .. ($#words - $position)) {
        # check if desired -- r -- size will be realised
        if ($r - scalar @{$prefix_word} <= scalar @words - $position) {
            # dereference 'prefix_word' and save it as an anonymous array reference
            $auxiliary_store[$_] = [@{$prefix_word}];
            # save current 'word' to what 'aux_store[$_]' is referencing
            push @{$auxiliary_store[$_]}, $words[$position];
            if (scalar @{$auxiliary_store[$_]} < $r) {
                # 1st argument is an array reference - add next word on
                repetitivePairing($auxiliary_store[$_], $position + 1);
            } else {
                # save a reference '$auxiliary_store[$_]' to '@comb_store'
                push(@comb_store$auxiliary_store[$_]);
            }
        }
        $position++;
    }
}

1;

Main Class

#!/usr/bin/perl;

use strict;
use warnings;

use COMBINATION;

my @subjects = ("Eno""Chidi""Olu""Ahmed""Osas""Gbeda");
my $r = 3;

# Use the combination module/class
my $combo = COMBINATION->new();

# $result receives an array reference of references
my $result = $combo->possibleWordCombinations(\@subjects$r);

print ("["join(", "@subjects), "] combination "$r":\n\n");
# for each array reference in a dereferenced '$result'
my $i = 0;
print (++$i": "join(", "@{$_}), "\n"for @{$result};
print ("\n\nNumber of ways is "scalar @{$result}, ".");

print "\n\n";



<< PreviousNext >>