You are on page 1of 2

The Main idea : nested loops

for example, instead of hard coding so many nested loops we can take an
complex function invocation to perform the same tasks just make the function
itself a parameter as the function definition
nsloop(){ for((${1}=${2}+1; ${1}<${3}; ++${1})); do eval eval
\\\$\{{4..${#}}\}; done; }
showed that,
for instance, instead of coding like this(step by step):
output(){ echo $i $j $k; }
for((i=1; i<3; ++i)); do
for((j=1; j<3; ++j)); do
for((k=1; k<3; ++k)); do
echo $i $j $k
done
done
done
to get the results:
111
112
121
122
211
212
221
222
we can just perform an complex function invocation like this:
nsloop(){ for((${1}=${2}+1; ${1}<${3}; ++${1})); do eval eval \\\$\{{4..${#}}\};
done; }
output(){ echo $i $j $k; }
nsloop i 0 3 nsloop j 0 3 nsloop k 0 3 output
to get the same results.
See https://github.com/yongye/shellutils/blob/master/permutation_combination
Just change the last line $(invoke) to invoke then run the script again you'll
know how
it works.

#!/bin/bash
# permutation_combination
arg0=-1
sep=${4:-.}
argv=${3:-p}
number=${2:-3}
eval ary=({1..${1:-4}})
length=${#ary[@]}
(( number > length )) && exit 1
((limit=length-number))
percom(){ loop i ${1} number${2} ${3} ${4} ${5}; }
invoke(){ echo $(percom ${argu} loop -1) prtcom $(percom
${argu}); }
permut(){ echo -n "${1} arg${i} ${2} "; (( ${#} != 0 )) && echo
-n " length "; }
combin(){ (( ${#} != 0 )) && echo -n "${1} arg$((i+1)) arg${i}
limit+$((i+1)) " || echo -n "arg$((i+1)) "; }
prtcom(){ num=0; for i in ${@}; do echo -n ${ary[${!i}]}; ((
++num != number )) && echo -n "${sep}"; done; echo; }
loop()
{
local arc arg
arg=${1//arg}
for((${1}=${2}+1; ${1}<${3}; ++${1})); do
if [[ ${1//[0-9]} == arg ]]; then
for((arc=1; arc!=arg; ++arc)); do
(( ${1} == arg${arc} )) && continue 2
done
fi
eval eval \\\$\{{4..${#}}\}
done
}
case ${argv} in
P|p) argu="-0 +1 permut" ;;
C|c) argu="-1 +0 combin" ;;
* ) exit 1
;;
esac
$(invoke)

You might also like