Permutations and combinations in Bash

This article about the generation of permutations and combinations in Bash using iteration will be the last of the series. Indeed, I have already written this kind of post for R, Python and Perl.

If you are not familiar with permutations and combinations, I invite you to read my first post. It contains the definition of permutations and combinations, an example, and the formulas to compute the number of possible subsets of a given length that can be selected from a set.

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 Bash.

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

Variables assignment

days=( "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" )
n=$((${#days[@]}-1))

Permutations with repetition

r = 2

for i in $(seq 0 $n); do
    for j in $(seq 0 $n); do
        echo "${days[i]}" - "${days[j]}"
    done
done

r = 3

for i in $(seq 0 $n); do
    for j in $(seq 0 $n); do
        for k in $(seq 0 $n); do
            echo "${days[i]}" - "${days[j]}" - "${days[k]}"
        done
    done
done

Permutations without repetition

r = 2

for i in $(seq 0 $n); do
    for j in $(seq 0 $n | grep -w -v $i);do
        echo "${days[i]}" - "${days[j]}"
    done
done

r = 3

for i in $(seq 0 $n); do
    for j in $(seq 0 $n | grep -w -v $i); do
        for k in $(seq 0 $n | grep -w -v -e $i -e $j); do
            echo "${days[i]}" - "${days[j]}" - "${days[k]}"
        done
    done
done

Combinations with repetition

r = 2

for i in $(seq 0 $n); do
    for j in $(seq $i $n); do
        echo "${days[i]}" - "${days[j]}"
    done
done

r = 3

for i in $(seq 0 $n); do
    for j in $(seq $i $n); do
        for k in $(seq $j $n); do
            echo "${days[i]}" - "${days[j]}" - "${days[k]}"
        done
    done
done

Combinations without repetition

r = 2

for i in $(seq 0 $n); do
    for j in $(seq $i $n | grep -w -v $i); do
        echo "${days[i]}" - "${days[j]}"
    done
done

r = 3

for i in $(seq 0 $n); do
    for j in $(seq $i $n | grep -w -v $i); do
        for k in $(seq $j $n | grep -w -v -e $i -e $j); do
            echo "${days[i]}" - "${days[j]}" - "${days[k]}"
        done
    done
done

Conclusion

In conclusion, the implementation of the four cases in Bash is quite similar to Perl, which is in my opinion less straightforward than in R! Finally, I hope that this series of blog posts about permutations and combinations are helpful to you!

Related posts

Comments

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

Leave a Reply