Lightweight Mathematical Permutations Using C# in Visual Studio Magazine

I wrote an article titled “Lightweight Mathematical Permutations Using C#” in the July 2022 issue of Microsoft Visual Studio Magazine. See https://visualstudiomagazine.com/articles/2022/07/05/lightweight-permutations-using-csharp.aspx.

A zero-based mathematical permutation of order n is a rearrangement of the integers 0 through n-1. For example, if n = 5, then two possible permutations are (0, 1, 2, 3, 4) and (3, 0, 4, 2, 1). The total number of permutations for order n is factorial(n), usually written as n! and calculated as n * (n-1) * (n-2) * . . 1. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.

The article presents a demo program. The demo illustrates how to create and display a permutation of order n, compute n! using the BigInteger type, display all permutations of order n using a Successor() function, and compute a specific permutation element directly.

Here’s the demo code for a Factorial() function:

using System.Numerics; 
static BigInteger Factorial(int n)
{
  if (n == 0 || n == 1)
    return BigInteger.One;

  BigInteger ans = BigInteger.Parse("1");  // alternative
  for (int i = 1; i <= n; ++i)
    ans *= i;
  return ans;
}

Permutations have no direct, immediate application in most software development scenarios, but once you know how permutations work, they can be used in many practical ways.



The study of permutations and probability was originally motivated by gambling, especially dice and card games. Here are four sets of dice made from natural materials. Left: malachite. Center-Left: obsidian. Center-Right: amethyst. Right: garnet.


This entry was posted in Miscellaneous. Bookmark the permalink.