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.
1
votes
Why ksh? Unix shells are not very good at these kinds of computations.
- Ned
is it the number of combination (so a statistic evaluation) or all the generated combination that you want ?
- NeronLeVelu
What do the symbols represent in this question?
- javaPlease42
@javaPlease I guess they render as ... something on some platforms, but like (I guess) you, I just see empty squares on my iPhone.
- tripleee
1 Answers
1
votes
@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
>