RosettaCodeData/Task/Combinations-and-permutations/Bracmat/combinations-and-permutations.bracmat
2023-10-02 18:11:16 -07:00

119 lines
2.7 KiB
Text

( C
= n k coef
. !arg:(?n,?k)
& (!n+-1*!k:<!k:?k|)
& 1:?coef
& whl
' ( !k:>0
& !coef*!n*!k^-1:?coef
& !k+-1:?k
& !n+-1:?n
)
& !coef
)
& ( compileBinomialFunctionThatDoesFloatingPointCalculations
=
. new
$ ( UFP
,
' ( (s.n) (s.k)
. "**************************************************************
*** Notice the difference between the following four lines ***
*** of code and the much shorter (!n+-1*!k:<!k:?k|) in ***
*** function C above. UFP grammar is simpler than usual ***
*** Bracmat grammar. UFP code is therefore less terse. ***
**************************************************************"
& !n+-1*!k:?n-k
& ( !n-k:<!k&!n-k:?k
|
)
& 1:?coef
& whl
' ( !k:>0
& !coef*!n*!k^-1:?coef
& !k+-1:?k
& !n+-1:?n
)
& !coef
)
)
)
& compileBinomialFunctionThatDoesFloatingPointCalculations$
: ?binom
& ( P
= n k result
. !arg:(?n,?k)
& !n+-1*!k:?k
& 1:?result
& whl
' ( !n:>!k
& !n*!result:?result
& !n+-1:?n
)
& !result
)
& ( compilePermutationFunctionThatDoesFloatingPointCalculations
=
. new
$ ( UFP
,
' ( (s.n) (s.k)
. !n+-1*!k:?k
& 1:?result
& whl
' ( !n:>!k
& !n*!result:?result
& !n+-1:?n
)
& !result
)
)
)
& compilePermutationFunctionThatDoesFloatingPointCalculations$
: ?permu
& 0:?i
& whl
' ( 1+!i:~>12:?i
& div$(!i.3):?k
& out$(!i P !k "=" P$(!i,!k))
)
& 0:?i
& whl
' ( 10+!i:~>60:?i
& div$(!i.3):?k
& out$(!i Cn !k "= " C$(!i,!k))
& out$(!i Cf !k "=" (binom..go)$(!i,!k))
)
& ( displayBig
=
. @(!arg:?show [50 ? [?length)
& !show "... (" !length+-50 " more digits)"
| !arg
)
& 5 50 500 1000 5000 15000:?is
& whl
' ( !is:%?i ?is
& div$(!i.3):?k
& out
$ ( str
$ (!i " Pn " !k " = " displayBig$(P$(!i,!k)))
)
& out
$ ( str
$ (!i " Pf " !k " = " (permu..go)$(!i,!k))
)
)
& 0:?i
& whl
' ( 100+!i:~>1000:?i
& div$(!i.3):?k
& out
$ ( str
$ (!i " Cn " !k " = " displayBig$(C$(!i,!k)))
)
& out
$ ( str
$ (!i " Cf " !k " = " (binom..go)$(!i,!k))
)
)
& all done;