Combinations and permutations: Difference between revisions
m
syntax highlighting fixup automation
SqrtNegInf (talk | contribs) m (→{{header|Perl}}: added output) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 28:
{{trans|C++}}
<
BigInt r = 1
V k = n - p
Line 44:
print(‘P(12,’i‘) = ’perm(12, i))
L(i) (10.<60).step(10)
print(‘C(60,’i‘) = ’comb(60, i))</
{{out}}
Line 70:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude_combinations_and_permutations.a68'''<
COMMENT REQUIRED by "prelude_combinations_and_permutations.a68" CO
Line 160:
END COMMENT
SKIP</
# -*- coding: utf-8 -*- #
Line 209:
printf(($"("g(0)" C "g(0)") = "g(0,1)$, r, first, r C first, $", "$));
printf(($"("g(0)" C "g(0)") = "g(0,1)$, r, second, r C second, $l$))
OD</
<pre>
A sample of Permutations from 1 to 12:
Line 262:
=={{header|Bracmat}}==
Bracmat cannot handle floating point numbers. Instead, this solution shows the first 50 digits and a count of the digits that are not shown.
<
= n k coef
. !arg:(?n,?k)
Line 317:
& out$(str$(!i " C " !k " = " displayBig$(C$(!i,!k))))
)
);</
Output:
<pre>1 P 0 = 1
Line 356:
=={{header|C}}==
Using big integers. GMP in fact has a factorial function which is quite possibly more efficient, though using it would make code longer.
<
void perm(mpz_t out, int n, int k)
Line 382:
gmp_printf("C(1000,969) = %Zd\n", x);
return 0;
}</
=={{header|C++}}==
{{libheader|Boost}}
Compiled with <code>g++-10 -Wall -std=c++03</code>, linked with <code>-lgmp</code>
<
#include <iostream>
Line 414:
return 0;
}</
{{out}}
<pre>P(12,1) = 12
Line 435:
=={{header|Common Lisp}}==
<
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
Line 451:
(a m (* a m)))
((= i k) a)))))
</syntaxhighlight>
=={{header|Crystal}}==
{{trans|Ruby}}
<
include Math
Line 494:
p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000
</syntaxhighlight>
{{out}}
<pre>
Line 510:
=={{header|D}}==
{{trans|Ruby}}
<
std.bigint, std.conv;
Line 535:
15_000.bigPermutation(1185).writeln;
writefln("%(%s\\\n%)", 15_000.permutation(74).text.chunks(50));
}</
{{out}}
<pre>79833600
Line 554:
=={{header|EchoLisp}}==
<
;; rename native functions according to task
(define-syntax-rule (Cnk n k) (Cnp n k))
Line 575:
→ 1029024198692120734765388598788124551227594950478035495578451793852872815678512303375588360
1398831219998720000000000000
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
def perm(n, k), do: product(n - k + 1 .. n)
Line 616:
end
Combinations_permutations.test</
{{out}}
Line 666:
{{trans|Haskell}}
<
-module(combinations_permutations).
Line 709:
io_lib:format("~s... (~p more digits)", [Shown, length(Hidden)])
end.
</syntaxhighlight>
Output:
Line 758:
=={{header|Factor}}==
As with Racket, these operations are built in and Factor has unlimited integers.
<
1000 10 nCk . ! 263409560461970212832400
1000 10 nPk . ! 955860613004397508326213120000</
=={{header|FreeBASIC}}==
{{trans|Visual Basic .NET}}
<
Dim As Long i
Dim As Longint z = 1
Line 826:
Print ""
Next i
Sleep</
=={{header|Go}}==
Go has arbitrary-length maths in the standard math/big library; no need for floating-point approximations at this level.
<syntaxhighlight lang="go">
package main
Line 896:
return c
}
</syntaxhighlight>
Output:
<pre>A sample of permutations from 1 to 12:
Line 943:
=={{header|Haskell}}==
The Haskell Integer type supports arbitrary precision so floating point approximation is not needed.
<
perm n k = product [n-k+1..n]
Line 981:
mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ]
</syntaxhighlight>
{{out}}
<pre style="font-size:80%">A sample of permutations from 1 to 12:
Line 1,032:
The sample here gives a few representative values to shorten the output.
<
write("P(4,2) = ",P(4,2))
write("P(8,2) = ",P(8,2))
Line 1,056:
every (p:=1) *:= (n-k+1) to n
return p
end</
Output:
Line 1,085:
Implementation:
<
P=: (%&!&x:~ * <:)"0</
! is a primitive, but we will give it a name (<code>C</code>) for this task.
Line 1,092:
Example use (P is permutations, C is combinations):
<
┌──┬─────────────────────────────────────────────────────────────┐
│P │1 2 3 4 5 6 7 8 9 10 11 12│
Line 1,138:
2.24185e96
700 C 800
3.41114e129</
=={{header|Java}}==
The second part of this task implies that the computations are performed in floating point arithmetic. However, the maximum value of a double in Java is 1.7976931348623157E308. Hence, larger computations would overflow. As a result, this task was interpreted so that “using” means “displayed”.
<syntaxhighlight lang="java">
import java.math.BigInteger;
Line 1,214:
}
</syntaxhighlight>
{{out}}
Line 1,279:
=={{header|jq}}==
Currently, jq approximates large integers by IEEE 754 64-bit floats, and only supports tgamma (true gamma). Thus beyond about 1e308 all accuracy is lost.
<
| reduce range($n-k+1; 1+$n) as $i (1; . * $i);
Line 1,298:
def big_permutation(k): log_permutation(k) | exp;
def big_combination(k): log_combination(k) | exp;</
'''Examples''':
12 | permutation(9) #=> 79833600
Line 1,316:
'''Functions'''
<syntaxhighlight lang="julia">
function Base.binomial{T<:FloatingPoint}(n::T, k::T)
exp(lfact(n) - lfact(n - k) - lfact(k))
Line 1,327:
⊞{T<:Real}(n::T, k::T) = binomial(n, k)
⊠{T<:Real}(n::T, k::T) = factorial(n, n-k)
</syntaxhighlight>
'''Main'''
<syntaxhighlight lang="julia">
function picknk{T<:Integer}(lo::T, hi::T)
n = rand(lo:hi)
Line 1,383:
println(@sprintf " %7.1f ⊞ %7.1f = %10.6e" n k n ⊞ k)
end
</syntaxhighlight>
{{out}}
Line 1,442:
=={{header|Kotlin}}==
As Kotlin/JVM can use the java.math.BigInteger class, there is no need to use floating point approximations and so we use exact integer arithmetic for all parts of the task.
<
import java.math.BigInteger
Line 1,482:
System.out.printf("%4d C %-3d = %s%s\n", n, k, s.take(40), e)
}
}</
{{out}}
Line 1,530:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module PermComb {
Form 80, 50
Line 1,597:
}
PermComb
</syntaxhighlight>
{{out}}
-- Permutations - from 1 to 12
Line 1,638:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
comb := proc (n::integer, k::integer)
return factorial(n)/(factorial(k)*factorial(n-k));
Line 1,645:
return factorial(n)/factorial(n-k);
end proc;
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Combination[n_,k_]:=Binomial[n,k]
Permutation[n_,k_]:=Binomial[n,k]k!
Line 1,655:
TableForm[Array[Combination,{6,6},{{10,60},{10,60}}],TableHeadings->{Range[10,60,10],Range[10,60,10]}]
{Row[{#,"P",#-2}," "],N@Permutation[#,#-2]}&/@{5,1000,5000,10000,15000}//Grid
{Row[{#,"C",#/2}," "],N@Combination[#,#/2]}&/@Range[100,1000,100]//Grid</
{{out}}
Line 1,699:
</pre>
Note that Mathematica can easily handle very big numbers with exact integer arithmetic:
<syntaxhighlight lang="mathematica">
Permutation[200000, 100000]
</syntaxhighlight>
{{out}}
The output is 516777 digits longs:
Line 1,709:
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П2 <-> П1 -> <-> П7 КПП7 С/П
ИП1 ИП2 - ПП 53 П3 ИП1 ПП 53 ИП3 / В/О
1 ИП1 * L2 21 В/О
ИП1 ИП2 - ПП 53 П3 ИП2 ПП 53 ИП3 * П3 ИП1 ПП 53 ИП3 / В/О
ИП1 ИП2 + 1 - П1 ПП 26 В/О
ВП П0 1 ИП0 * L0 56 В/О</
''Input'': ''x ^ n ^ k В/О С/П'', where ''x'' = 8 for permutations; 20 for permutations with repetitions; 26 for combinations; 44 for combinations with repetitions.
Line 1,721:
=={{header|Nim}}==
<
proc perm(n, k: int32): BigInt =
Line 1,740:
echo "P(1000, 969) = ", perm(1000, 969)
echo "C(1000, 969) = ", comb(1000, 969)</
=={{header|PARI/GP}}==
<
permExact(m,n)=factorback([m-n+1..m]);
combExact=binomial;
Line 1,752:
sample(combExact, 10, 60);
sample(permApprox, 5, 15000);
sample(combApprox, 100, 1000);</
{{out}}
<pre>?sample(permExact, 1, 12);
Line 1,781:
As with the Raku code, some special handling was done for those values which would have overflowed the native floating point type.
<
use warnings;
Line 1,831:
sprintf "%.8Fe%+d", exp($x - $e * log(10)), $e;
}
</syntaxhighlight>
{{out}}
<pre style="height:50ex">A sample of Permutations from 1 to 12
Line 1,878:
Translation of Raku/Sidef, same results<br>
Update: there are now builtin routines k_perm(n,k) and choose(n,k), slightly more efficient equivalents of P() and C() respectively.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">P</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
Line 1,932:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"C(%d,%d) = %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">,</span><span style="color: #000000;">to_s</span><span style="color: #0000FF;">(</span><span style="color: #000000;">C_approx</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">p</span><span style="color: #0000FF;">))})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 1,975:
=={{header|Python}}==
==={{libheader|SciPy}}===
<
from scipy.misc import factorial as fact
Line 2,004:
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact))
</syntaxhighlight>
{{out}}
Line 2,037:
=={{header|R}}==
R has most of this built in. The documentation for choose warns that it only calculates its result directly if k is small. Skimming [https://github.com/wch/r-source/blob/trunk/src/nmath/choose.c what appears to be the source code] suggests that 29 is the highest "small" k. This means that we can solve both tasks with little more than R's choose.
<
print(perm(seq(from = 3, to = 12, by = 3), seq(from = 2, to = 8, by = 2)))
print(choose(seq(from = 10, to = 60, by = 10), seq(from = 3, to = 18, by = 3)))
print(perm(seq(from = 1500, to = 15000, by = 1500), seq(from = 55, to = 100, by = 5)))
print(choose(seq(from = 100, to = 1000, by = 150), seq(from = 70, to = 100, by = 5)))</
{{out}}
<pre>> print(perm(seq(from = 3, to = 12, by = 3), seq(from = 2, to = 8, by = 2)))
Line 2,062:
there is no need for a floating point estimate:
<syntaxhighlight lang="racket">
#lang racket
(require math)
Line 2,070:
(C 1000 10) ; -> 263409560461970212832400
(P 1000 10) ; -> 955860613004397508326213120000
</syntaxhighlight>
(I'll spare this page from yet another big listing of samples...)
Line 2,083:
Notice that Raku can process arbitrary long integers, though. So it's not clear whether using floating points is useful in this case.
<syntaxhighlight lang="raku"
multi C($n, $k) { P($n, $k) / [*] 1 .. $k }
Line 2,127:
my $p = $n div 3;
say "C($n, $p) = ", C($n, $p, :float);
}</
{{out}}
<pre>Exact results:
Line 2,169:
=={{header|REXX}}==
The hard part of this REXX program was coding the '''DO''' loops for the various ranges.
<
numeric digits 100 /*use 100 decimal digits of precision. */
Line 2,212:
if x-y <y then y=x - y /*switch things around for speed. */
call .combPerm /*call subroutine to do heavy lifting. */
return _ / !(y) /*just perform one last division. */</
'''output'''
<pre>
Line 2,265:
=={{header|Ruby}}==
Float calculation as Tcl.
<
class Integer
Line 2,303:
#Fixnum has no maximum:
p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000
</syntaxhighlight>
Ruby's Arrays have a permutation and a combination method which result in (lazy) enumerators. These Enumerators have a "size" method, which returns the size of the enumerator, or nil if it can’t be calculated lazily. (Since Ruby 2.0)
<
=={{header|Scheme}}==
<
(define (combinations n k)
(do ((i 0 (+ 1 i))
Line 2,334:
(display "C(1000,1000) = ") (display (combinations 1000 1000)) (newline)
(display "C(15000,14998) = ") (display (combinations 15000 14998)) (newline)
</syntaxhighlight>
{{out}}
Line 2,355:
=={{header|Sidef}}==
{{trans|Raku}}
<
func C(n, k) { binomial(n, k) }
Line 2,399:
var p = n//3
say "C(#{n}, #{p}) = #{C_approx(n, p)}"
}</
{{out}}
<pre>
Line 2,444:
The '''[https://www.stata.com/help.cgi?mf_comb comb]''' function is builtin. Here is an implementation, together with perm:
<
return(exp(lnfactorial(n)-lnfactorial(k)-lnfactorial(n-k)))
}
Line 2,450:
real scalar perm(n, k) {
return(exp(lnfactorial(n)-lnfactorial(n-k)))
}</
=={{header|Swift}}==
Line 2,458:
Using AttaSwift's BigInt
<
func permutations(n: Int, k: Int) -> BigInt {
Line 2,512:
print("\(i) C \(k) = \(res.prefix(40))\(extra)")
}</
{{out}}
Line 2,561:
Tcl doesn't allow the definition of new infix operators, so we define <math>P</math> and <math>C</math> as ordinary functions. There are no problems with loss of significance though: Tcl has supported arbitrary precision integer arithmetic since 8.5.
{{tcllib|math}}
<
proc tcl::mathfunc::P {n k} {
set t 1
Line 2,585:
proc tcl::mathfunc::fC {n k} {
expr {exp(lnGamma($n+1) - lnGamma($n-$k+1) - lnGamma($k+1))}
}</
Demonstrating:
<
puts "A sample of Permutations from 1 to 12:"
for {set i 4} {$i <= 12} {incr i} {
Line 2,612:
set iii [expr {$i - int(sqrt($i))}]
puts "$i C $ii = [expr {fC($i,$ii)}], $i C $iii = [expr {fC($i,$iii)}]"
}</
{{out}}
<pre>
Line 2,663:
=={{header|VBScript}}==
<
dim i,j
Wscript.StdOut.WriteLine "-- Long Integer - Permutations - from 1 to 12"
Line 2,721:
comb=perm(x,y)/fact(y)
end if
end function 'comb</
{{out}}
<pre style="height:40ex">
Line 2,758:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2013}}
<
Imports System.Numerics 'BigInteger
Module CombPermRc
Line 2,826:
End Function 'CombBig
End Module</
{{out}}
<pre style="height:40ex">
Line 2,865:
{{libheader|Wren-fmt}}
{{libheader|Wren-trait}}
<
import "/fmt" for Fmt
import "/trait" for Stepped
Line 2,907:
var e = (l <= 40) ? "" : "... (%(l - 40) more digits)"
Fmt.print("$4d C $-3d = $s$s", n, k, s.take(40).join(), e)
}</
{{out}}
|