iliankostov

Permutation in C#

Oct 7th, 2015
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. namespace Permutations
  2. {
  3.     using System;
  4.     using System.Linq;
  5.  
  6.     internal class Permutations
  7.     {
  8.         private static int countOfPermutations;
  9.  
  10.         private static void Main()
  11.         {
  12.             Console.Write("n = ");
  13.             int n = int.Parse(Console.ReadLine());
  14.             var array = Enumerable.Range(1, n).ToArray();
  15.  
  16.             Permutate(array);
  17.  
  18.             Console.WriteLine("Total permutations: {0}", countOfPermutations);
  19.         }
  20.  
  21.         private static void Permutate(int[] array, int startIndex = 0)
  22.         {
  23.             if (startIndex >= array.Length - 1)
  24.             {
  25.                 Console.WriteLine(string.Join(", ", array));
  26.                 countOfPermutations++;
  27.             }
  28.             else
  29.             {
  30.                 Permutate(array, startIndex + 1);
  31.                 for (int i = startIndex + 1; i < array.Length; i++)
  32.                 {
  33.                     Swap(ref array[startIndex], ref array[i]);
  34.                     Permutate(array, startIndex + 1);
  35.                     Swap(ref array[startIndex], ref array[i]);
  36.                 }
  37.             }
  38.         }
  39.  
  40.         private static void Swap(ref int i, ref int j)
  41.         {
  42.             if (i == j)
  43.             {
  44.                 return;
  45.             }
  46.  
  47.             i ^= j;
  48.             j ^= i;
  49.             i ^= j;
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment