Advertisement
rali_kumanova

Permutations Of Elements

Jan 15th, 2013
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. class PermutationsOfElements
  5. {
  6. static void Main()
  7. {
  8. /*
  9. 19. * Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Example:
  10. n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
  11. */
  12.  
  13. Console.Write("Enter N: ");
  14. int n = int.Parse(Console.ReadLine());
  15. int[] permutation = new int[n];
  16. Permutations(permutation, 0, n);
  17. }
  18.  
  19. static void PrintPermutation(int[] array, int lenght)
  20. {
  21. for (int i = 0; i < lenght; i++)
  22. {
  23. Console.Write("{0} ", array[i]);
  24. }
  25. Console.WriteLine();
  26. }
  27.  
  28. static void Permutations(int[] array, int index, int n)
  29. {
  30. if (index == array.Length)
  31. {
  32. CheckDifferentElements(array, array.Length);
  33. }
  34. else
  35. {
  36. for (int i = 1; i <= n; i++)
  37. {
  38. array[index] = i;
  39. Permutations(array, index + 1, n);
  40. }
  41. }
  42. }
  43.  
  44. static void CheckDifferentElements(int[] arr, int n)
  45. {
  46. var result = arr.Distinct();
  47. result.ToArray();
  48. if (result.Count() == n)
  49. {
  50. PrintPermutation(result.ToArray(), n);
  51. }
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement