简体   繁体   English

KornShell从一组n个对象生成k个对象的组合数量

[英]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? 有人可以帮助使用KornShell(ksh)获取代码来从具有n个对象的集合中生成k个对象的组合数为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. 例如,一次取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 is right, sh is not the right place to be doing this @Ned Nowotny是正确的,sh不是执行此操作的正确位置

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
> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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