简体   繁体   中英

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

Could anyone help to get code using KornShell (ksh) to generate the number of combinations of k objects from a set with n objects is n C k? For example, the combinations of {1,2,3,4} taken k=2 at a time are {1,2}, {1,3}, {1,4}, {2,3}, {2,4}, {3,4}, for a total of 6 = 4 / [(2)(4-2) ] subsets.

@Ned Nowotny is right, sh is not the right place to be doing this

that said, here's the recursive form:

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

and here's the faster factorial form:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM