algorithm - the logic behind bash power set function -
the function (output power set of given input)
p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; echo -e "$1 $r\n$r"; done }
test input
p $(echo -e "1 2 3")
test output
1 2 3 2 3 1 3 3 1 2 2 1
i have difficulty grasping recursion in following code. tried understand placing variables inside of code denote level of recursion , order of execution, still puzzled.
here things can tell far:
- the subshell's output not shown on final output, gets redirected read command via pipe
- the
echo
command appends new line of output
the order of execution see is:
- p (1 2 3) -> 1 followed combination of output below\n combination of output below
- p (2 3) -> 2 3\n3\n
- p (3) -> 3
- p () ->
so think should have p(2) instead of p(3) on execution #3, how happen? since shift
goes in 1 direction.
if use "p(1 2 3 4)" input, part shows "1 2 3" in output confuses me.
the use of -e
in echo
command seems me pure obfuscation, since have been written:
p() { [ $# -eq 0 ] && echo || (shift; p "$@") | while read r ; echo $1 $r echo $r done }
in other words, "for every set in power set of first argument (shift; p "$@")
, output both set , without first argument."
the bash function works setting chain of subshells, each 1 reading next one, this, each box subshell , below it, i've shown output reads each line of input: (i used ""
make "nothing" visible. =>
means "call"; <-
means "read".)
+---------+ +-------+ +-------+ +-------+ | p 1 2 3 | ==> | p 2 3 | ==> | p 3 | ==> | p | +---------+ +-------+ +-------+ +-------+ 1 2 3 "" <--+-- 2 3 "" <---+-- 3 "" <-----+-- "" 2 3 "" <-/ / / 1 3 "" <--+-- 3 "" <-/ / 3 "" <-/ / 1 2 "" <--+-- 2 "" <---+-- "" <-/ 2 "" <-/ / 1 "" <--+-- "" <-/ "" <-/
Comments
Post a Comment