Combining elements with echo

I need to prepare a simple script to generate all possible permutations of a set of items stored in a variable in groups of n items (being n parameterizable), the simplest solution that came to mind was to use multiple loops depending on the selected group length. But I thought it would be more elegant to use the capabilities of the echo command to create combinations, i.e.

echo {1,2}{1,2}
    11 12 21 22

      

So using this method, I'm trying to do a general way of doing it, using a list of items (eg {1,2}) and a count of items as inputs. It will be something like this:

set={1,2,3,4}
group=3
for ((i=0; i<$group; i++));
do
  repetition=$set$repetition
done

      

So in this particular case, at the end of the loop, the repeat variable has the value {1,2,3,4} {1,2,3,4} {1,2,3,4}. But I cannot find a way to use this variable to create combinations using the echo command. I've tried several things like:

echo $repetition
echo $(echo $repetition)

      

I'm stuck on it, I would appreciate any advice or help on this.

+3


source to share


2 answers


You can use:

bash -c "echo "$repetition""
111 112 113 114 121 122 123 124 131 132 133 134 141 142 143 144 211 212 213 214 221 222 223 224 231 232 233 234 241 242 243 244 311 312 313 314 321 322 323 324 331 332 333 334 341 342 343 344 411 412 413 414 421 422 423 424 431 432 433 434 441 442 443 444

      



Or use eval

insteadbash -c

+1


source


If you want k combinations for all k , this script combination might help:

#!/bin/bash

POWER=$((2**$#))
BITS=`seq -f '0' -s '' 1 $#`

while [ $POWER -gt 1 ];do
  POWER=$(($POWER-1))
  BIN=`bc <<< "obase=2; $POWER"`
  MASK=`echo $BITS | sed -e "s/0\{${#BIN}\}$/$BIN/" | grep -o .`
  POS=1; AWK=`for M in $MASK;do
    [ $M -eq 1 ] && echo -n "print \\$\${POS};"
    POS=$(($POS+1))
    done;echo`
  awk -v ORS=" " "{$AWK}" <<< "$@" | sed 's/ $//'
done

      

Example:



./combination ⚪ ⛔ ⚫
⚪ ⛔ ⚫
⚪ ⛔
⚪ ⚫
⛔ ⚫

      

There is an empty set too, trust me.

0


source







All Articles