Advertisement
Klaxon

[C# Arrays] Number Permutations

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