Advertisement
Ms_Nenova

C# Arrays Permutations by given N

Jan 18th, 2013
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class ArrayPermutations
  5. {
  6.     static void SwapValues<T>(T[] arr, int startPos, int endPos)            //Here we will swap the values of the array.
  7.     {
  8.         if (startPos != endPos)
  9.         {
  10.             T temporary = arr[startPos];                                    //We need this to keep the value from the starting position.
  11.             arr[startPos] = arr[endPos];
  12.             arr[endPos] = temporary;
  13.         }
  14.     }
  15.     static IEnumerable<T[]> Permutations<T>(T[] arr, int startIndex = 0)    //Here we will calculate the permutations with an iterator method.
  16.     {
  17.         if (startIndex + 1 == arr.Length)
  18.         {
  19.             yield return arr;                                              //We use a yield return statement to return each element one at a time.
  20.         }
  21.         else
  22.         {
  23.             foreach (var item in Permutations(arr, startIndex + 1))        //We go to the next value.
  24.             {
  25.                 yield return item;
  26.             }
  27.             for (var i = startIndex + 1; i < arr.Length; i++)              //In the loop we use the swapping method to change position of the values.
  28.             {
  29.                 SwapValues(arr, startIndex, i);
  30.                 foreach (var item in Permutations(arr, startIndex + 1))
  31.                 {
  32.                     yield return item;
  33.                 }
  34.                 SwapValues(arr, startIndex, i);
  35.             }
  36.         }
  37.     }
  38.     static void Main()
  39.     {
  40.         Console.Write("Enter a number N to make permutations:");
  41.         int N = int.Parse(Console.ReadLine());
  42.         int[] arrayOfNumbers = new int[N];
  43.         for (int i = 1; i <= N; i++)
  44.         {
  45.             arrayOfNumbers[i - 1] = i;
  46.         }
  47.  
  48.         foreach (var item in Permutations(arrayOfNumbers))
  49.         {
  50.             Console.WriteLine(string.Join(", ", item));
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement