Permutations and combinations in Perl

Before going through the generation of permutations and combinations in Perl using iteration, I invite you to read my first post if you are not familiar with permutations and combinations. You will find there the definitions, an example of all the possible subsets of 2 items selected from a set of 5 items and the formulas to compute the number of possible subsets in each case.

Moreover, I have already described the generation of permutations and combinations in R and in Python. In the four next sections, we will use r loops to generate all the possible subsets of r elements from a given set of n elements in Perl. I will take as example a selection of 2 items (r = 2) and a selection of 3 items (r = 3).

cheat sheet of the permutations and combinations in Perl using iteration
Cheat sheet of the permutations and combinations in Perl using iteration

Variables assignment

@months = ("January", "February", "March", "April", "May");
$n = @months-1;

Permutations with repetition

r = 2

for $i (0..$n){
    for $j (0..$n){
        print("@months[$i]"," - ","@months[$j]","\n");
    }
}

r = 3

for $i (0..$n){
    for $j (0..$n){
        for $k (0..$n){
            print("@months[$i]"," - ","@months[$j]"," - ","@months[$k]","\n");
        }
    }
}

Permutations without repetition

r = 2

for $i (0..$n){
    for $j (grep {!/$i/} (0..$n)){
        print("@months[$i]"," - ","@months[$j]","\n");
    }
}

r = 3

for $i (0..$n){
    for $j (grep {!/$i/} (0..$n)){
        for $k (grep {!/$i/ && !/$j/} (0..$n)){
            print("@months[$i]"," - ","@months[$j]"," - ","@months[$k]","\n");
        }
    }
}

Combinations with repetition

r = 2

for $i (0..$n){
    for $j ($i..$n){
        print("@months[$i]"," - ","@months[$j]","\n");
    }
}

r = 3

for $i (0..$n){
    for $j ($i..$n){
        for $k ($j..$n){
            print("@months[$i]"," - ","@months[$j]"," - ","@months[$k]","\n");
        }
    }
}

Combinations without repetition

r = 2

for $i (0..$n){
    for $j (grep {!/$i/} ($i..$n)){
        print("@months[$i]"," - ","@months[$j]","\n");
    }
}

r = 3

for $i (0..$n){
    for $j (grep {!/$i/} ($i..$n)){
        for $k (grep {!/$i/ && !/$j/} ($j..$n)){
            print("@months[$i]"," - ","@months[$j]"," - ","@months[$k]","\n");
        }
    }
}

Conclusion

In conclusion, I found the implementation of the four cases in Perl easier than in Python but a bit more difficult than in R. I hope that this post is helpful to you!

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply