## C# || How To Generate Next Permutation From Array Using C#

The following is a module with functions which demonstrates how to generate the next permutation from an array using C#.

1. Next Permutation – Problem Statement

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

Example 1:

``` Input: nums = [1,2,3] Output: [1,3,2] ```

Example 2:

``` Input: nums = [3,2,1] Output: [1,2,3] ```

Example 3:

``` Input: nums = [1,1,5] Output: [1,5,1] ```

Example 4:

``` Input: nums = [1] Output: [1] ```

2. Next Permutation – Solution

The following is a solution which demonstrates how to generate the next permutation from an array

``` 2. Next Permutation - Solution C# // ============================================================================ // Author: Kenneth Perkins // Date: Oct 27, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to generate the next permutation // ============================================================================ public class Solution { public void NextPermutation(int[] nums) { // Starting from the end, look for the first index that is not in descending order var startIndex = nums.Length - 2; while (startIndex >= 0) { // Find first decreasing element if (nums[startIndex] < nums[startIndex + 1]) { break; } --startIndex; } if (startIndex >= 0) { // Starting from the end, look for the first element greater than the start index int endIndex = nums.Length - 1; while (endIndex > startIndex) { // Find first greater element if (nums[endIndex] > nums[startIndex]) { break; } --endIndex; } // Swap first and last elements Swap(ref nums[startIndex], ref nums[endIndex]); } // Reverse the array Reverse(nums, startIndex + 1); } private void Reverse(int[] nums, int startIndex) { for (int start = startIndex, end = nums.Length - 1; start < end; ++start, --end) { Swap(ref nums[start], ref nums[end]); } } private void Swap(ref int a, ref int b) { var tmp = a; a = b; b = tmp; } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 // ============================================================================//    Author: Kenneth Perkins//    Date:   Oct 27, 2021//    Taken From: http://programmingnotes.org///    File:  Solution.cs//    Description: Demonstrates how to generate the next permutation// ============================================================================public class Solution {    public void NextPermutation(int[] nums) {        // Starting from the end, look for the first index that is not in descending order        var startIndex = nums.Length - 2;         while (startIndex >= 0) {            // Find first decreasing element            if (nums[startIndex] < nums[startIndex + 1]) {                break;            }            --startIndex;        }         if (startIndex >= 0) {            // Starting from the end, look for the first element greater than the start index            int endIndex = nums.Length - 1;             while (endIndex > startIndex) {                // Find first greater element                if (nums[endIndex] > nums[startIndex]) {                    break;                }                --endIndex;            }             // Swap first and last elements            Swap(ref nums[startIndex], ref nums[endIndex]);        }         // Reverse the array        Reverse(nums, startIndex + 1);    }     private void Reverse(int[] nums, int startIndex) {        for (int start = startIndex, end = nums.Length - 1; start < end; ++start, --end) {            Swap(ref nums[start], ref nums[end]);        }    }     private void Swap(ref int a, ref int b) {        var tmp = a;        a = b;        b = tmp;    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

``` [1,3,2] [1,2,3] [1,5,1] [1] ```

## C# || How To Generate Unique Permutations From Array With Duplicate Values Using C#

The following is a module with functions which demonstrates how to generate unique permutations from an array with duplicate values using C#.

1. Permute Unique – Problem Statement

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

Example 1:

``` Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] ```

Example 2:

``` Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] ```

2. Permute Unique – Solution

The following is a solution which demonstrates how to generate unique permutations from an array with duplicate values.

``` 2. Permute Unique - Solution C# // ============================================================================ // Author: Kenneth Perkins // Date: Oct 27, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to generate unique permutations // ============================================================================ public class Solution { private List<IList<int>> result = new List<IList<int>>(); public IList<IList<int>> PermuteUnique(int[] nums) { // Sort Array Array.Sort(nums); Generate(nums, new List<int>(), new bool[nums.Length]); return result; } private void Generate(int[] nums, List<int> combination, bool[] visited) { if (combination.Count == nums.Length) { result.Add(new List<int>(combination)); return; } for (int index = 0; index < nums.Length; ++index) { // Check to see if this number has been visited if (visited[index]) { continue; } else if (index > 0 && nums[index] == nums[index - 1] && !visited[index - 1]) { continue; } // Set that this index has been visited visited[index] = true; // Add this number to the combination combination.Add(nums[index]); // Keep generating permutations Generate(nums, combination, visited); // Unset that this index has been visited visited[index] = false; // Remove last item as its already been explored combination.RemoveAt(combination.Count - 1); } } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 // ============================================================================//    Author: Kenneth Perkins//    Date:   Oct 27, 2021//    Taken From: http://programmingnotes.org///    File:  Solution.cs//    Description: Demonstrates how to generate unique permutations// ============================================================================public class Solution {    private List<IList<int>> result = new List<IList<int>>();     public IList<IList<int>> PermuteUnique(int[] nums) {        // Sort Array        Array.Sort(nums);        Generate(nums, new List<int>(), new bool[nums.Length]);        return result;    }     private void Generate(int[] nums, List<int> combination, bool[] visited) {        if (combination.Count == nums.Length) {            result.Add(new List<int>(combination));            return;        }         for (int index = 0; index < nums.Length; ++index) {            // Check to see if this number has been visited            if (visited[index]) {                continue;            } else if (index > 0 && nums[index] == nums[index - 1] && !visited[index - 1]) {                continue;            }             // Set that this index has been visited            visited[index] = true;             // Add this number to the combination            combination.Add(nums[index]);             // Keep generating permutations            Generate(nums, combination, visited);             // Unset that this index has been visited            visited[index] = false;             // Remove last item as its already been explored            combination.RemoveAt(combination.Count - 1);        }    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

``` [[1,1,2],[1,2,1],[2,1,1]] [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] ```

## C# || How To Generate Permutations From Array With Distinct Values Using C#

The following is a module with functions which demonstrates how to generate permutations from an array with distinct values using C#.

1. Permute – Problem Statement

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:

``` Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] ```

Example 2:

``` Input: nums = [0,1] Output: [[0,1],[1,0]] ```

Example 3:

``` Input: nums = [1] Output: [[1]] ```

2. Permute – Solution

The following is a solution which demonstrates how to generate permutations from an array with distinct values.

``` 2. Permute - Solution C# // ============================================================================ // Author: Kenneth Perkins // Date: Oct 27, 2021 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to generate permutations // ============================================================================ public class Solution { private List<IList<int>> result = new List<IList<int>>(); public IList<IList<int>> Permute(int[] nums) { Generate(nums, new List<int>(), new bool[nums.Length]); return result; } private void Generate(int[] nums, List<int> combination, bool[] visited) { if (combination.Count == nums.Length) { result.Add(new List<int>(combination)); return; } for (int index = 0; index < nums.Length; ++index) { // Check to see if this index has been visited if (visited[index]) { continue; } // Set that this index has been visited visited[index] = true; // Add this number to the combination combination.Add(nums[index]); // Keep generating permutations Generate(nums, combination, visited); // Unset that this index has been visited visited[index] = false; // Remove last item as its already been explored combination.RemoveAt(combination.Count - 1); } } }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344 // ============================================================================//    Author: Kenneth Perkins//    Date:   Oct 27, 2021//    Taken From: http://programmingnotes.org///    File:  Solution.cs//    Description: Demonstrates how to generate permutations// ============================================================================public class Solution {    private List<IList<int>> result = new List<IList<int>>();     public IList<IList<int>> Permute(int[] nums) {        Generate(nums, new List<int>(), new bool[nums.Length]);        return result;    }     private void Generate(int[] nums, List<int> combination, bool[] visited) {        if (combination.Count == nums.Length) {            result.Add(new List<int>(combination));            return;        }         for (int index = 0; index < nums.Length; ++index) {            // Check to see if this index has been visited            if (visited[index]) {                continue;            }             // Set that this index has been visited            visited[index] = true;             // Add this number to the combination            combination.Add(nums[index]);             // Keep generating permutations            Generate(nums, combination, visited);             // Unset that this index has been visited            visited[index] = false;             // Remove last item as its already been explored            combination.RemoveAt(combination.Count - 1);        }    }}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

``` [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] [[0,1],[1,0]] [[1]] ```