Advertisement
bankoff

permutations

Jul 7th, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.10 KB | None | 0 0
  1. // 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.  
  5. using System;
  6.  
  7. class AllPermutationsOfNNumbers
  8. {
  9.     static void Main()
  10.     {
  11.         //reading the input data from the console
  12.         uint numberN;
  13.         do
  14.         {
  15.             Console.Write("Please enter the number N: ");
  16.         }
  17.         while (!uint.TryParse(Console.ReadLine(), out numberN));
  18.  
  19.         if (numberN < 1)
  20.         {
  21.             Console.WriteLine("This combination is imposible");
  22.         }
  23.         else
  24.         {
  25.             // calculating the number of all combinations http://www.kombinatoruka.hit.bg/__7.html
  26.             for (uint i = 0; i < Math.Pow(numberN, numberN); i++)
  27.             {
  28.                 uint conv = i;
  29.                 uint[] arrayForPrint = new uint[numberN];
  30.                 uint[] arrayForSort = new uint[numberN];
  31.                 bool print = true;
  32.  
  33.                 //convert from decimal to n-number system
  34.                 for (uint j = 0; j < numberN; j++)
  35.                 {
  36.                     arrayForPrint[numberN - j - 1] = conv % numberN;
  37.                     arrayForSort[numberN - j - 1] = conv % numberN;
  38.                     conv = conv / numberN;
  39.                 }
  40.  
  41.                 //checking for the printing of the combination
  42.                 Array.Sort(arrayForSort);
  43.                 for (int j = 1; j < arrayForSort.Length; j++)
  44.                 {
  45.                     if (arrayForSort[j] == arrayForSort[j - 1])
  46.                     {
  47.                         print = false;
  48.                     }
  49.                 }
  50.  
  51.                 // print result
  52.                 if (print)
  53.                 {
  54.                     Console.Write("{0}{1}", '{', arrayForPrint[0] + 1);
  55.                     for (uint j = 1; j < numberN; j++)
  56.                     {
  57.                         Console.Write(", {0}", arrayForPrint[j] + 1);
  58.                     }
  59.                     Console.WriteLine("}");
  60.                 }
  61.             }
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement