Debian Codegraph @

src/Data/Nat/Combinatorics/Base.agda

raw
1 ------------------------------------------------------------------------
2 -- The Agda standard library
3 --
4 -- Combinatorics operations
5 ------------------------------------------------------------------------
6
7 {-# OPTIONS --cubical-compatible --safe #-}
8
9 module Data.Nat.Combinatorics.Base where
10
11 open import Data.Bool.Base using (if_then_else_)
12 open import Data.Nat.Base
13 open import Data.Nat.Properties using (_!≢0)
14
15 -- NOTE: These operators are not implemented as efficiently as they
16 -- could be. See the following link for more details.
17 --
18 -- https://math.stackexchange.com/questions/202554/how-do-i-compute-binomial-coefficients-efficiently
19
20 ------------------------------------------------------------------------
21 -- Permutations / falling factorial
22
23 -- The number of ways, including order, that k objects can be chosen
24 -- from among n objects.
25
26 -- n P k = n ! / (n ∸ k) !
27
28 infixl 6.5 _P′_ _P_
29
30 -- Base definition. Only valid for k ≤ n.
31
32 _P′_ : ℕ → ℕ → ℕ
33 n P′ zero = 1
34 n P′ (suc k) = (n ∸ k) * (n P′ k)
35
36 -- Main definition. Valid for all k as deals with boundary case.
37
38 _P_ : ℕ → ℕ → ℕ
39 n P k = if k ≤ᵇ n then n P′ k else 0
40
41 ------------------------------------------------------------------------
42 -- Combinations / binomial coefficient
43
44 -- The number of ways, disregarding order, that k objects can be chosen
45 -- from among n objects.
46
47 -- n C k = n ! / (k ! * (n ∸ k) !)
48
49 infixl 6.5 _C′_ _C_
50
51 -- Base definition. Only valid for k ≤ n.
52
53 _C′_ : ℕ → ℕ → ℕ
54 n C′ k = (n P′ k) / k !
55 where instance _ = k !≢0
56
57 -- Main definition. Valid for all k.
58 -- Deals with boundary case and exploits symmetry to improve performance.
59
60 _C_ : ℕ → ℕ → ℕ
61 n C k = if k ≤ᵇ n then n C′ (k ⊓ (n ∸ k)) else 0