问题
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