簡體   English   中英

KornShell從一組n個對象生成k個對象的組合數量

[英]KornShell to generate the number of combinations of k objects from a set with n objects

有人可以幫助使用KornShell(ksh)獲取代碼來從具有n個對象的集合中生成k個對象的組合數為n C k嗎? 例如,一次取k = 2的{1,2,3,4}的組合為{1,2},{1,3},{1,4},{2,3},{2, 4},{3,4},總共6 =4/ [(2)(4-2)]個子集。

@Ned Nowotny是正確的,sh不是執行此操作的正確位置

也就是說,這是遞歸形式:

> function cr { integer n=$1 k=$2; if ((k==1)); then print $n; elif ((k==n)); then print 1; else print $(($(cr $((n-1)) $((k-1))) + $(($(cr $((n-1)) $k))))); fi; }
> cr 4 2
6
> 

這是更快的階乘形式:

> function fact { integer x=$1 f=1; while ((x>0)) do : $((f*=x--)); done; print $f; }
> function cf { integer n=$1 k=$2; print $(($(fact $n)/($(fact $k)*$(fact $(($n-$k)))))); }
> cf 4 2
6
> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM