AWK power set implementation

此生再无相见时 提交于 2019-12-13 08:06:26

问题


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?


回答1:


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.




回答2:


Here is a solution adapted from Rosetta Code:

function al(br, ch, de) {
  while (br) {
    ch--
    if (br % 2)
      de = de $(sprintf("%c", 49 + ch)) FS
    br = int(br / 2)
  }
  return de
}
{
  for (ec = 0; ec <= 2 ^ NF - 1; ec++) {
    print al(ec, NF)
  }
}

Usage:

echo x y z | power-set.awk

Example




回答3:


In GNU AWK (due to and, lshift and the way of split:)

$ cat program.awk
BEGIN {
    n=split(s,a,"")
    for(i=1;i<2^n;i++) {
        for(j=1;j<=n;j++)
            if(and(lshift(1,(j-1)),i))
                printf "%s", a[j]
        print ""
    }
}

Usage:

$ awk -v s="abc" -f program.awk
a
b
ab
c
ac
bc
abc


来源:https://stackoverflow.com/questions/40966428/awk-power-set-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!