Arrangement

_An arrangement (or permutation of k elements) is an ordered set of k elements chosen from n distinct elements, where the order of selection matters.

Formal definition:

Let there be a set of n distinct elements. An arrangement of n elements taken k at a time is any ordered set of k elements selected from the given set.

Important:

Examples:

Formula for counting the number of arrangements:

The number of arrangements of n elements taken k at a time is denoted A(n, k) and is calculated by the formula:

\(A(n, k) = \frac{n!}{(n - k)!}\)

Example calculation:

\(A(5, 3) = \frac{5!}{(5 - 3)!} = \frac{5 \cdot 4 \cdot 3 \cdot 2 \cdot 1}{2 \cdot 1} = 5 \cdot 4 \cdot 3 = 60\)

Arrangements of a given length

Given a collection of elements. Generate all arrangements of a given length.

Taken from the article "Combinatorial Algorithms in Scala"

Algorithm:

Example:

Consider the example with list = List(1, 2) and n = 2:

Estimation:

Code:

extension [A](list: List[A])
  def xvariations(n: Int): List[List[A]] =
    def mixmany(a: A, lists: List[List[A]]): List[List[A]] =
      lists match
        case Nil      => Nil
        case hd :: tl => foldone(a, hd) ::: mixmany(a, tl)

    def foldone(a: A, lists: List[A]): List[List[A]] =
      (1 to lists.length).foldLeft(List(a :: lists)): (acc, i) =>
        mixone(i, a, lists) :: acc

    def mixone(i: Int, a: A, lists: List[A]): List[A] =
      lists.slice(0, i) ::: (a :: lists.slice(i, lists.length))

    if n > list.length then Nil
    else
      list match
        case Nil         => Nil
        case _ if n == 1 => list.map(List(_))
        case hd :: tl =>
          mixmany(hd, tl.xvariations(n - 1)) ::: tl.xvariations(n)
  end xvariations
end extension

List("a", "b", "c").xvariations(2)
// List(List("b", "a"), List("a", "b"),
//      List("c", "a"), List("a", "c"),
//      List("c", "b"), List("b", "c"))

All arrangements

Given a collection of elements. Generate all possible arrangements from this collection of all possible lengths.

The total number of arrangements in a set of length n can be calculated as follows:

\(P_{n}^{} = A_{n}^{n} = n!\)

Taken from the article "Combinatorial Algorithms in Scala"

Algorithm:

Estimation:

Code:

def xpermutations: List[List[A]] = xvariations(l.length)

List("a", "b", "c").xpermutations
// List(
//   List("c", "b", "a"),
//   List("c", "a", "b"),
//   List("a", "c", "b"),
//   List("b", "c", "a"),
//   List("b", "a", "c"),
//   List("a", "b", "c")
// )

Links: