awk permutations and combinations

hello,

I'm reading this thread, in which there is this code :

awk '
function comb(v,i) {
    for(i in A) {
      delete A;
      if(length(A))
         comb((v?v"+":x)i)
      else print v"+"i
      A;
    }
}
{ A[$0] }
END {
   comb();
} ' infile

but I can't understand where does v come from, how it gets assigned...

In awk , function "parameters" that are not used by the caller are considered local. man awk :

ok, this doesn't appear in gawk's man, but it does in mawk's

thank you

Sure? man gawk :

As RudiC said, variables that aren't supplied as arguments when an awk function is called are local variables and are initialized to 0 (if used as a number) or to an empty string (if used as a string). Variables that are supplied as arguments when a function is called are still local variables to that function but are initialized from the value supplied.

The unusual thing about the comb () function in this code is that it is called recursively and neither argument is specified the first time it is called (in the END clause), but passes itself a value for the 1st argument (but not the 2nd) when it calls itself recursively. Although there is never an assignment to the variable v in that script, the recursive calls to comb () made by comb () effectively assign a value to v by passing in a value for one argument that is based on the value passed in plus one element in the array created by reading values from the file named infile .

1 Like

/Perhaps for a little more clarity, I should have passed a blank string into comb() from the END clause:

awk '
function comb(v,i) {
    for(i in A) {
      delete A;
      if(length(A))
         comb((v ? v "+" : "") i)
      else print v "+" i
      A;
    }
}
{ A[$0] }
END { comb("") } ' infile
3 Likes