Advertisement
Hristo_B

Arrays.Permutations

Jun 30th, 2013
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. using System;
  2.  
  3. class PrintPermutations
  4. {
  5.     //* Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N].
  6.     //Example: n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
  7.  
  8.     static void Switch(ref int first, ref int second)
  9.     {
  10.         int temp = first;
  11.         first = second;
  12.         second = temp;
  13.     }
  14.     static int counter = 1;
  15.     static void Permutation(int[] array, int current, int length)
  16.     {
  17.         if (current == length)
  18.         {
  19.  
  20.             Console.WriteLine("[{0}]  {1}", counter, string.Join(", ", array));
  21.             counter++;
  22.         }
  23.         else
  24.         {
  25.             for (int i = current; i <= length; i++)
  26.             {
  27.                 Switch(ref array[i], ref array[current]);
  28.                 Permutation(array, current + 1, length);
  29.                 Switch(ref array[i], ref array[current]);
  30.             }
  31.         }
  32.     }
  33.  
  34.     static void Main(string[] args)
  35.     {
  36.         Console.Write("N = ");
  37.         int n = int.Parse(Console.ReadLine());
  38.         int[] arrayOfNumbers = new int[n];
  39.  
  40.         for (int i = 0; i < n; i++)
  41.         {
  42.             arrayOfNumbers[i] = i + 1;
  43.         }
  44.         Console.WriteLine("All permutations from 1 to {0} are:", n);
  45.         Permutation(arrayOfNumbers, 0, arrayOfNumbers.Length - 1);
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement