Combinations and permutations: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Perl}}: added output)
m (syntax highlighting fixup automation)
Line 28:
{{trans|C++}}
 
<langsyntaxhighlight lang="11l">F perm(=n, p)
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))</langsyntaxhighlight>
 
{{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'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
COMMENT REQUIRED by "prelude_combinations_and_permutations.a68" CO
Line 160:
END COMMENT
 
SKIP</langsyntaxhighlight>'''File: test_combinations_and_permutations.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- 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</langsyntaxhighlight>'''Output:'''
<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.
<langsyntaxhighlight Bracmatlang="bracmat">( ( C
= n k coef
. !arg:(?n,?k)
Line 317:
& out$(str$(!i " C " !k " = " displayBig$(C$(!i,!k))))
)
);</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="c">#include <gmp.h>
 
void perm(mpz_t out, int n, int k)
Line 382:
gmp_printf("C(1000,969) = %Zd\n", x);
return 0;
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|Boost}}
Compiled with <code>g++-10 -Wall -std=c++03</code>, linked with <code>-lgmp</code>
<langsyntaxhighlight lang="cpp">#include <boost/multiprecision/gmp.hpp>
#include <iostream>
 
Line 414:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>P(12,1) = 12
Line 435:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight Lisplang="lisp">(defun combinations (n k)
(cond ((or (< n k) (< k 0) (< n 0)) 0)
((= k 0) 1)
Line 451:
(a m (* a m)))
((= i k) a)))))
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">require "big"
include Math
Line 494:
p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 510:
=={{header|D}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="d">import std.stdio, std.mathspecial, std.range, std.algorithm,
std.bigint, std.conv;
 
Line 535:
15_000.bigPermutation(1185).writeln;
writefln("%(%s\\\n%)", 15_000.permutation(74).text.chunks(50));
}</langsyntaxhighlight>
{{out}}
<pre>79833600
Line 554:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; rename native functions according to task
(define-syntax-rule (Cnk n k) (Cnp n k))
Line 575:
→ 1029024198692120734765388598788124551227594950478035495578451793852872815678512303375588360
1398831219998720000000000000
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Combinations_permutations do
def perm(n, k), do: product(n - k + 1 .. n)
Line 616:
end
 
Combinations_permutations.test</langsyntaxhighlight>
 
{{out}}
Line 666:
{{trans|Haskell}}
 
<langsyntaxhighlight lang="erlang">
-module(combinations_permutations).
 
Line 709:
io_lib:format("~s... (~p more digits)", [Shown, length(Hidden)])
end.
</syntaxhighlight>
</lang>
 
Output:
Line 758:
=={{header|Factor}}==
As with Racket, these operations are built in and Factor has unlimited integers.
<langsyntaxhighlight lang="factor">USING: math.combinatorics prettyprint ;
 
1000 10 nCk . ! 263409560461970212832400
1000 10 nPk . ! 955860613004397508326213120000</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{trans|Visual Basic .NET}}
<langsyntaxhighlight lang="freebasic">Function PermBig(x As Long, y As Long) As ULongint
Dim As Long i
Dim As Longint z = 1
Line 826:
Print ""
Next i
Sleep</langsyntaxhighlight>
 
 
=={{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">
<lang go>
package main
 
Line 896:
return c
}
</syntaxhighlight>
</lang>
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.
<langsyntaxhighlight lang="haskell">perm :: Integer -> Integer -> Integer
perm n k = product [n-k+1..n]
 
Line 981:
mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ]
 
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight lang="unicon">procedure main()
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</langsyntaxhighlight>
 
Output:
Line 1,085:
Implementation:
 
<langsyntaxhighlight Jlang="j">C=: !
P=: (%&!&x:~ * <:)"0</langsyntaxhighlight>
 
! 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):
 
<langsyntaxhighlight Jlang="j"> P table 1+i.12
┌──┬─────────────────────────────────────────────────────────────┐
│P │1 2 3 4 5 6 7 8 9 10 11 12│
Line 1,138:
2.24185e96
700 C 800
3.41114e129</langsyntaxhighlight>
 
=={{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">
<lang Java>
import java.math.BigInteger;
 
Line 1,214:
}
</syntaxhighlight>
</lang>
 
{{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.
<langsyntaxhighlight lang="jq">def permutation(k): . as $n
| 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;</langsyntaxhighlight>
'''Examples''':
12 | permutation(9) #=> 79833600
Line 1,316:
 
'''Functions'''
<syntaxhighlight lang="julia">
<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>
</lang>
 
'''Main'''
<syntaxhighlight lang="julia">
<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>
</lang>
 
{{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.
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.math.BigInteger
Line 1,482:
System.out.printf("%4d C %-3d = %s%s\n", n, k, s.take(40), e)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,530:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module PermComb {
Form 80, 50
Line 1,597:
}
PermComb
</syntaxhighlight>
</lang>
{{out}}
-- Permutations - from 1 to 12
Line 1,638:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<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>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[Combination,Permutation]
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</langsyntaxhighlight>
 
{{out}}
Line 1,699:
</pre>
Note that Mathematica can easily handle very big numbers with exact integer arithmetic:
<syntaxhighlight lang="mathematica">
<lang Mathematica>
Permutation[200000, 100000]
</syntaxhighlight>
</lang>
{{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 В/О</langsyntaxhighlight>
 
''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}}==
<langsyntaxhighlight lang="nim">import bigints
 
proc perm(n, k: int32): BigInt =
Line 1,740:
 
echo "P(1000, 969) = ", perm(1000, 969)
echo "C(1000, 969) = ", comb(1000, 969)</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">sample(f,a,b)=for(i=1,4, my(n1=random(b-a)+a,n2=random(b-a)+a); [n1,n2]=[max(n1,n2),min(n1,n2)]; print(n1", "n2": "f(n1,n2)))
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);</langsyntaxhighlight>
{{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.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 1,831:
sprintf "%.8Fe%+d", exp($x - $e * log(10)), $e;
}
</syntaxhighlight>
</lang>
{{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.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,975:
=={{header|Python}}==
==={{libheader|SciPy}}===
<langsyntaxhighlight lang="python">from __future__ import print_function
 
from scipy.misc import factorial as fact
Line 2,004:
k = N-2
print('%iC%i =' % (N, k), comb(N, k, exact))
</syntaxhighlight>
</lang>
 
{{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.
<langsyntaxhighlight lang="rsplus">perm <- function(n, k) choose(n, k) * factorial(k)
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)))</langsyntaxhighlight>
{{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>
#lang racket
(require math)
Line 2,070:
(C 1000 10) ; -> 263409560461970212832400
(P 1000 10) ; -> 955860613004397508326213120000
</syntaxhighlight>
</lang>
 
(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" perl6line>multi P($n, $k) { [*] $n - $k + 1 .. $n }
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);
}</langsyntaxhighlight>
{{out}}
<pre>Exact results:
Line 2,169:
=={{header|REXX}}==
The hard part of this REXX program was coding the &nbsp; '''DO''' &nbsp; loops for the various ranges.
<langsyntaxhighlight lang="rexx">/*REXX program compute and displays a sampling of combinations and permutations. */
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. */</langsyntaxhighlight>
'''output'''
<pre>
Line 2,265:
=={{header|Ruby}}==
Float calculation as Tcl.
<langsyntaxhighlight lang="ruby">include Math
 
class Integer
Line 2,303:
#Fixnum has no maximum:
p 15000.permutation(74) #=> 896237613852967826239917238565433149353074416025197784301593335243699358040738127950872384197159884905490054194835376498534786047382445592358843238688903318467070575184552953997615178973027752714539513893159815472948987921587671399790410958903188816684444202526779550201576117111844818124800000000000000000000
</syntaxhighlight>
</lang>
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)
<langsyntaxhighlight lang="ruby">(1..60).to_a.combination(53).size #=> 386206920</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="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>
</lang>
 
{{out}}
Line 2,355:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func P(n, k) { n! / ((n-k)!) }
func C(n, k) { binomial(n, k) }
 
Line 2,399:
var p = n//3
say "C(#{n}, #{p}) = #{C_approx(n, p)}"
}</langsyntaxhighlight>
{{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:
 
<langsyntaxhighlight lang="stata">real scalar comb1(n, k) {
return(exp(lnfactorial(n)-lnfactorial(k)-lnfactorial(n-k)))
}
Line 2,450:
real scalar perm(n, k) {
return(exp(lnfactorial(n)-lnfactorial(n-k)))
}</langsyntaxhighlight>
 
=={{header|Swift}}==
Line 2,458:
Using AttaSwift's BigInt
 
<langsyntaxhighlight lang="swift">import BigInt
 
func permutations(n: Int, k: Int) -> BigInt {
Line 2,512:
 
print("\(i) C \(k) = \(res.prefix(40))\(extra)")
}</langsyntaxhighlight>
 
{{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}}
<langsyntaxhighlight lang="tcl"># Exact integer versions
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))}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl"># Using the exact integer versions
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)}]"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,663:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Combinations and permutations - vbs - 10/04/2017
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</langsyntaxhighlight>
{{out}}
<pre style="height:40ex">
Line 2,758:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2013}}
<langsyntaxhighlight lang="vbnet">' Combinations and permutations - 10/04/2017
Imports System.Numerics 'BigInteger
Module CombPermRc
Line 2,826:
End Function 'CombBig
 
End Module</langsyntaxhighlight>
{{out}}
<pre style="height:40ex">
Line 2,865:
{{libheader|Wren-fmt}}
{{libheader|Wren-trait}}
<langsyntaxhighlight lang="ecmascript">import "/big" for BigInt
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)
}</langsyntaxhighlight>
 
{{out}}
10,339

edits