简体   繁体   中英

Generate combinations of elements with echo

I need to prepare a simple script to generate all the permutations possible of a set of elements stored in a variable in groups of n elements (being n parameterizable), the easiest solution which came to mind was using several loops depending on the selected length of the group. But I thought that it would be more elegant taking advantage of the ability of echo command to generate combinations, that is

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

So using this method, I'm trying to achieve a general way to do it, using as input parameters the list of elements (for example {1,2}) and the number of elements. It would be something like it:

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 repetition variable has the value {1,2,3,4}{1,2,3,4}{1,2,3,4}. But I'm not able to find the way to use this variable to produce the combinations using the echo command. I've tried, several things like:

echo $repetition
echo $(echo $repetition)

I'm stucked on it, I'd appreciate any tip or help on that.

If you need k-combinations for all k , this combination script can 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 ⚪ ⛔ ⚫
⚪ ⛔ ⚫
⚪ ⛔
⚪ ⚫
⚪
⛔ ⚫
⛔
⚫

The empty set is there too, trust me.

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 else use eval instead of bash -c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM