【使用 AWK 撰寫 Recusive Program】
$ vim rec.awk
awk ‘
BEGIN {
x = 35
y = 45
test_variable(x)
printf(“Return to main: arg1 = %d, x = %d, y = %d, z = %d n”, arg1, x, y, z)
}
function test_variable(x) {
arg1 += 10
y++
printf(“Inside the function: arg1 = %d, x = %d, y = %d, z = %dn”, arg1, x, y, z)
}
‘ $*
-> vim 命令模輸入 “:wq” (存檔離開)
$ chmod +x rec.awk
$ ./rec.awk
Inside the function: arg1 = 10, x = 35, y = 46, z = 0
Return to main: arg1 = 10, x = 35, y = 46, z = 0
$ vim premu.awk
awk ‘
BEGIN {
print “請輸入排列的元素,各元素間請用空白隔開”
getline
premutation($0, “”)
printf(“n共 %d 種排列方式n”, counter)
}
function premutation(main_lst, buffer, new_main_list, nf, i, j) {
$0 = main_lst
nf = NF
if (nf == 1) {
print buffer main_lst
counter++
return
} else for (i=1; i<=nf; i++) {
$0 = main_lst
new_main_lst = “”
for (j=1; j<=nf; j++)
if (j != i) new_main_lst = new_main_lst ” ” $j
premutation(new_main_lst, buffer ” ” $i)
}
}
‘ $*
-> vim 命令模輸入 “:wq” (存檔離開)
$ chmod +x premu.awk
$ ./premu.awk
請輸入排列的元素,各元素間請用空白隔開
a b c
a b c
a c b
b a c
b c a
c a b
c b a
共 6 種排列方式
【資料參考來源】