Combination of numbers

Hello Group,

I have a file of data that contain
1
2
3
4
5

I request you help with a shell script for generate all posible combination of these numbers with the following output:

Example:
1 + 2 + 3 + 4 + 5 =
2 + 2 + 3 + 4 + 5 =
3 + 2 + 3 + 4 + 5 =

Thanks in advance.

Carlos

Ruby(1.9.1+)

 $ ruby -e 'a=File.read("file").split; a.permutation(a.length).to_a.each {|x| puts x.join}' 
1 Like

Hello kurumi / Forum,

Thanks for your prompt response. I have Cygwin and I was unable to execute the ruby command.
Do you have an "awk" script version that I can use instead of this script?

I really appreciate it your help

Carlos

try:

paste -sd " " file | awk '{split($0,a," ")}END{
for(i=1;i<=NF;i++) {printf $i;for(j=2;j<=NF;j++) {printf "+"a[j]}print "="}
}'
1+2+3+4+5=
2+2+3+4+5=
3+2+3+4+5=
4+2+3+4+5=
5+2+3+4+5=
1 Like

If you mean permutations, rather than combinations, this can be done relatively easily using recursion in a shell that has local variables:

#!/bin/ksh
function perm {
  typeset p=$1 s=$2 i
  for i in "${NR[@]}"
  do
    if [ $p -eq 1 ]; then
      printf "%s%s=\n" "$s" "$i"
    else
      perm $((p-1)) "$s$i+"
    fi
  done
}

while read nr; do
  NR[$((i++))]=$nr
done < infile
perm ${#NR[@]}

The trouble is the exponential increase in the time required with increasing numbers

With awk:

awk 'function perm(p,s,     i) {
       for(i=1;i<=n;i++)
         if(p==1)
           printf "%s%s=\n",s,A
         else
           perm(p-1,s A"+")
     }
     {
       A[++n]=$1
     }
     END{
       perm(n)
     }' infile

So I think this kind of exercise is best left to a general programming language

1 Like

Inho this not an example of combinations or an example of permutations.
What is the process?

My understand is, this is homework again.

Hello Scrutinizer / Group ,

The shell script of awk that you made calculate all possible permutations in this case 3125 (5 numbers) but i want to have only the 126 possible combination. For now it does not matter the specific order of the numbers.

I would appreciate it you can help me with the awk script of combination.

Regards,
Carlos