Advertisement
sashomaga

All Permutations

Jan 8th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. //Write a program that reads a number N and generates and prints all the permutations
  5. //of the numbers [1 … N]. Example:
  6. //n = 3 => {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
  7. class Program
  8. {
  9.     static List<string> list = new List<string>();
  10.     static StringBuilder builder = new StringBuilder();
  11.  
  12.     static void Main()
  13.     {
  14.         Console.Write("Enter number [1...N]: ");
  15.         int num = int.Parse(Console.ReadLine());
  16.  
  17.         int[] myArray = new int[num];
  18.  
  19.         for (int i = 0; i < num; i++)
  20.         {
  21.             myArray[i] = i + 1;
  22.         }
  23.  
  24.         Permutation(myArray, 0);
  25.  
  26.         foreach (var item in list)
  27.         {
  28.             Console.WriteLine(item);
  29.         }
  30.     }
  31.  
  32.     private static void Permutation(int[] myArray, int position)
  33.     {
  34.         if (position == myArray.Length - 1)
  35.         {
  36.             for (int i = 0; i < myArray.Length; i++)
  37.             {
  38.                 builder.Append(myArray[i]).Append(" ");
  39.             }
  40.             list.Add(builder.ToString());
  41.             builder.Clear();
  42.         }
  43.         else
  44.         {
  45.             for (int i = position; i < myArray.Length; i++)
  46.             {
  47.                 Swap(ref myArray[i], ref myArray[position]);
  48.                 Permutation(myArray, position + 1);
  49.                 Swap(ref myArray[i], ref myArray[position]);
  50.             }
  51.         }
  52.     }
  53.  
  54.     private static void Swap(ref int a, ref int b)
  55.     {
  56.         if (a == b)
  57.         {
  58.             return;
  59.         }
  60.         a ^= b;
  61.         b ^= a;
  62.         a ^= b;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement