ellapt

T7.19.PermutationsOfInts

Jan 15th, 2013
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. class PermutationsOfInts
  2. {
  3. static void Main()
  4. {
  5. string inputVar;
  6. int n;
  7. Console.WriteLine(" Read number n, generate \n and print all permutations of the numbers [1....n]");
  8. do
  9. {
  10. Console.Write("Enter array length: ");
  11. }
  12. while (!(int.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  13.  
  14. int[] arrayOfints = new int[n];
  15. bool[] repeated = new bool[arrayOfints.Length];
  16.  
  17. Permutation(arrayOfints, repeated, 0);
  18. }
  19.  
  20. static void PrintResult(int[] array)
  21. {
  22. int n = array.Length;
  23. for (int i = 0; i < n; i++) Console.Write(array[i] + 1 + (i == n - 1 ? "\n" : " "));
  24. }
  25.  
  26. static void Permutation(int[] arr, bool[] repFlag, int i)
  27. {
  28. if (i == arr.Length)
  29. {
  30. PrintResult(arr);
  31. return;
  32. }
  33.  
  34. for (int j = 0; j < arr.Length; j++)
  35. {
  36. if (repFlag[j]) continue;
  37. arr[i] = j;
  38. repFlag[j] = true;
  39. Permutation(arr, repFlag, i + 1);
  40. repFlag[j] = false;
  41. }
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment