usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Calculating Permutations - \(^nP_r\) (Possible Ways of Arrangement) using C#



Permutation in C#

A permutation refers to the number of possible arrangements of a set of objects where order matters. Permutations are widely used in mathematics, computer science, and programming problems that involve arranging data, generating sequences, or exploring all possible outcomes.

In this tutorial, we explain the mathematical concept of permutations and demonstrate how to generate permutations in C# using clear algorithms and practical code examples.

What Is a Permutation? | Mathematics Explanation for C# Kids

In mathematics, a permutation is an ordered arrangement of objects selected from a set. Because order is important, rearranging the same elements produces a different permutation.

For example, the arrangements ABC and BAC are considered different permutations of the same three elements.

Permutations commonly appear in:

  • Combinatorics
  • Algorithm design
  • Password and key generation
  • Game logic and simulations
  • Search and optimization problems

In the unlikely scenario that the Teacher wants to see just how any four pupils, from a group of six (6), could be seated on a four-person desk; what this Teacher would be doing in essence is called Permutation (\(^nP_r\)).


Permutation Formula (\(^nP_r\)) | Maths Explanation for C# Kids

The number of permutations of selecting r objects from n distinct objects is calculated using the formula:

$$ ^nP_r = \frac{n!}{(n - r)!} $$

Where:

  • n is the total number of objects
  • r is the number of objects selected
  • ! denotes factorial

This formula is useful when determining how many possible ordered arrangements exist before implementing a permutation algorithm in code.

Permutation With and Without Repetition | Maths Explanation for C# Kids

  • Permutation without repetition: Each element can appear only once in an arrangement.
  • Permutation with repetition: Elements may repeat, increasing the total number of possible arrangements.

The example below demonstrates permutations without repetition, which is the most common use case in programming exercises.


Permutation vs Combination in C#: What's the Difference?

Students often confuse permutations with combinations.

ConceptOrder MattersExample
PermutationYesABC ≠ BAC
CombinationNoABC = BAC

It is easy to confuse permutations and combinations. The key takeaway is:

  • Permutations (\(^nP_r\)): Use these when the order is important (e.g., a combination lock or race results).
  • Combinations (\(^nC_r\)): Use these when only the group members matter (e.g., picking a committee).

When solving C# problems involving ordered arrangements, permutations must be used. If order does not matter, combinations are more appropriate.

Understanding this distinction is essential when implementing mathematical algorithms in code.


Generating Permutations Using C#

In programming, permutations are often generated by systematically rearranging elements in an array. C# provides a flexible environment for implementing permutation algorithms using recursion or backtracking.

The following approach demonstrates how to generate all permutations of an array in C#.

C# Permutation Algorithm (\(^nP_r\))

The C# algorithm for Permutation - \(^nP_r\), possible ways of arrangement - will simply be based on that of combination.

All that is needed after combination is a rotation or shuffle of members of each possible combination result.
This shuffle simply involves interchanging the elements of the combination group of size, r, to take all possible positions starting from the extreme right to extreme left.

This is how our Permutation code in C# will work.

Create a new C# class file;
Call it Permutation
Type out the adjoining C# code for Permutation (\(^nP_r\)).


Advice: You might want to keep the mother-class size (n) and the group-size (r) small to avoid the C# permutation code taking too long.
As a rule-of-thump, DO NOT ASK QUESTIONS YOU DON'T WANT TO KNOW THE ANSWER TO.


Why Use C# for Combinatorics?

Using a C# math library or custom script allows you to build dynamic educational tools and interactive solvers. Our tool above uses this logic to give you instant results for any \(^nP_r\) calculation.

Applications of Permutations in C# Programming

Permutations are used in many real-world programming scenarios, including:

  • Generating all possible test cases
  • Exploring solution spaces in algorithms
  • Cryptography and security
  • Scheduling and optimization problems
  • Educational simulations

Summary: C# Permutation Algorithm

Permutations are a powerful concept in both mathematics and programming. With these C# permutation tutorials, you can calculate \(^nP_r\), generate permutations of arrays or strings, and apply them to real-world problems.

For example, calculating possible arrangements in C# can help determine seating orders, password combinations, or sequence generation.










C# Code for Permutation - Class File

using System.Collections.Generic;

namespace Miscellaneous
{
    class Permutation : Combination
    {
        private List<string[]> local_store;
        protected List<string[]> perm_store;
        private int index;

        public Permutation() : base()
        {
        }

        // till the ground for shuffle to grind on
        public List<string[]> possibleWordPermutations(List<string> candidates, int size) {
            perm_store = new List<string[]>();
            possibleWordCombinations(candidates, size);
            // illegal 'r' value
            if (comb_store.Count == 0 || r == 1) {
                    perm_store = comb_store;
            }
            else {
                List<string[]> last_two;
                last_two = new List<string[]>(){ new string[]{ """" }, new string[]{ """" } };
                for (int i = 0; i < comb_store.Count; i++) {
                    index = r - 1;
                    // copy up last two elements of 'comb_store[i]'
                    last_two[0][0] = last_two[1][1] = comb_store[i][index--];
                    last_two[0][1] = last_two[1][0] = comb_store[i][index--];
                    local_store = new List<string[]>();
                    local_store.Add(last_two[0]);
                    local_store.Add(last_two[1]);
                    if (r > 2) {
                        shuffleWord(local_store, i);
                    }
                    perm_store.AddRange(local_store);
                }
            }
            return perm_store;
        }

        private void shuffleWord(List<string[]> arg_store, int i) {
            local_store = new List<string[]>();
            List<string> members;
            for (int j = 0; j < arg_store.Count; j++) {
                members = new List<string>();
                members.AddRange(arg_store[j]);
                // add 'index' 'comb_store[i]' element to this list of members
                members.Add(comb_store[i][index]);

                string temp_char;
                int shift_index = members.Count;
                // shuffle this pack of words
                while (shift_index > 0) {
                    // skip if already in store
                    if (!local_store.Contains(members.ToArray())) {
                        local_store.Add(members.ToArray());
                    }
                    // interchange these two neighbours
                    if (--shift_index > 0 && !members[shift_index].Equals(members[shift_index - 1])) {
                        temp_char = members[shift_index];
                        members[shift_index] = members[shift_index - 1];
                        members[shift_index - 1] = temp_char;
                    }
                }
            }
            // Are there any elements left? repeat if yes
            if (index-- > 0) {
                shuffleWord(local_store, i);
            }
        }
    }
}


C# Code for Permutation - Main Class

using System;
using System.Collections.Generic;

namespace Miscellaneous
{
    class Program
    {
        static void Main(string[] args)
        {
            List<String> goods;
            goods = new List<String>() { "Eno""Chidi""Olu""Ahmed""Osas""Gbeda" };
            Permutation perm = new Permutation();
            List<String[]> result = perm.possibleWordPermutations(goods, 5);
            // print choices and operation
            Console.Write("[ ");
            foreach (string choice in perm.words)
            {
                Console.Write(choice + "; ");
            }
            Console.WriteLine("] permutation " + perm.r + ":" + Environment.NewLine);
            // print out permutations nicely
            int i = 0;
            foreach (string[] set in result)
            {
                Console.Write(++i + ": ");
                foreach (string member in set)
                {
                    Console.Write(member + "; ");
                }
                Console.WriteLine();
            }
            Console.WriteLine(Environment.NewLine + "Number of ways is " + result.Count + ".");
        }
    }
}





<< PreviousNext >>