Guest User

Print all permutations of an array

a guest
Nov 15th, 2011
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.12 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Permutations
  6. {
  7.     class Program
  8.     {
  9.         static int[] arr = new int[] { 1, 2, 3, 4 };
  10.  
  11.         static void Main(string[] args)
  12.         {
  13.             Perms(arr.ToList());
  14.         }
  15.  
  16.         public static void Perms<T>(List<T> list)
  17.         {
  18.             PermsRecursive(new List<T>(), list);
  19.         }
  20.  
  21.         private static void PermsRecursive<T>(List<T> perm, List<T> list)
  22.         {
  23.             if (list.Count == 0)
  24.             {
  25.                 Print(perm);
  26.             }
  27.             else
  28.                 foreach (var p in list)
  29.                 {
  30.                     perm.Add(p);
  31.                     List<T> temp = new List<T>(list);
  32.                     temp.Remove(p);
  33.                     PermsRecursive(perm, temp);
  34.                     perm.Remove(perm.Last());
  35.                 }
  36.         }
  37.  
  38.         private static void Print<T>(IEnumerable<T> arr)
  39.         {
  40.             foreach (var a in arr)
  41.             {
  42.                 Console.Write(a.ToString());
  43.             }
  44.             Console.WriteLine();
  45.         }
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment