Search code examples
shellunixawkpowerset

AWK power set implementation


This page provides a power set implementation in shell, and here is my take on it:

pa() {
  if [ "$#" = 0 ]
  then echo
  else (
    shift
    pa "$@"
  ) | while read qu
    do printf '%s %s\n%s\n' "$1" "$qu" "$qu"
    done
  fi
}
pa x y z

I thought it was interesting that the author of the above page made this comment:

no nice AWK solution. You are welcome to email me one: <his email>

Can this not be done in AWK, or does the shell just do a better job here?


Solution

  • Here is another AWK approach:

    echo a b c | awk '{for(i=0;i<2^NF;i++) {
                         for(j=0;j<NF;j++)
                            if(and(i,(2^j))) printf "%s ",$(j+1)
                         print ""}}'
    
    a
    b
    a b
    c
    a c
    b c
    a b c
    

    If your AWK doesn't have the and() function, replace it with int(i/(2^j))%2.