Last active
October 22, 2024 16:19
-
-
Save skchronicles/ec58f2b8d7af351ed59f354861768af5 to your computer and use it in GitHub Desktop.
Unique possible combinations bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
function unique_combinations() { | |
# Returns all unique possible combinations | |
# of a collection of elements of a given length, | |
# to return all possible unique combinations, | |
# set the last argument equal to the length of | |
# the input collection, see example below: | |
# @Input $1 to (N-1): Set of items to permutate | |
# @Input $N: Cardinality of the unique combination sets | |
# @Example: | |
# $ unique_combinations A B C 3 | |
# > A | |
# > B | |
# > C | |
# > A B | |
# > A C | |
# > B C | |
# > A B C | |
# Check if GNU parallel is installed | |
command -V parallel &> /dev/null || \ | |
{ cat <<< 'Error: missing GNU parallel, exiting now!' 1>&2; return 1; } | |
# Get all the args except the last | |
items=("${@:1:$(($#-1))}") | |
# bash get length of an array | |
n="${@: -1}" | |
( for i in $(seq 1 $n); do | |
# Building GNU parallel | |
# commands to generate | |
# unique combinations | |
# of cardinality N | |
echo -ne "\nparallel --plus echo {choose_k}" | |
for j in $(seq 1 $i); do | |
echo -n " ::: ${items[@]}"; | |
done | |
# Add a trailing newline | |
# char, remove empty line, | |
# exec the GNU parallel cmd | |
done; echo ) | awk 'NF' | bash | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python-based implementation
This python-based implementation is orders of magnitude (20-30x times) faster than the GNU parallel implementation above.