Advertisement
stybbe

Permutations of a String

Sep 9th, 2013
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.87 KB | None | 0 0
  1. using System;
  2.  
  3. namespace permutation
  4. {
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             string derp = "1234";
  10.             perm(derp, 0, derp.Length);
  11.  
  12.             Console.ReadKey();
  13.         }
  14.  
  15.         static void perm(string a, int k, int n)
  16.         {
  17.             if (k == n)
  18.             {
  19.                 Console.WriteLine(a);
  20.             }
  21.             else
  22.             {
  23.                 // Strings are immutable objects, so you can't replace a given character in the string.
  24.                 char[] charArr = a.ToCharArray();
  25.                 for (int i = k; i < n; i++)
  26.                 {
  27.                     var t = charArr[k];
  28.                     charArr[k] = charArr[i];
  29.                     charArr[i] = t;
  30.                     perm(new string(charArr), k + 1, n);
  31.                 }
  32.             }
  33.         }
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement