Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- class PermutationsOfElements
- {
- static void Main()
- {
- /*
- 19. * Write a program that reads a number N and generates and prints all the permutations of the numbers [1 … N]. Example:
- n = 3 {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
- */
- Console.Write("Enter N: ");
- int n = int.Parse(Console.ReadLine());
- int[] permutation = new int[n];
- Permutations(permutation, 0, n);
- }
- static void PrintPermutation(int[] array, int lenght)
- {
- for (int i = 0; i < lenght; i++)
- {
- Console.Write("{0} ", array[i]);
- }
- Console.WriteLine();
- }
- static void Permutations(int[] array, int index, int n)
- {
- if (index == array.Length)
- {
- CheckDifferentElements(array, array.Length);
- }
- else
- {
- for (int i = 1; i <= n; i++)
- {
- array[index] = i;
- Permutations(array, index + 1, n);
- }
- }
- }
- static void CheckDifferentElements(int[] arr, int n)
- {
- var result = arr.Distinct();
- result.ToArray();
- if (result.Count() == n)
- {
- PrintPermutation(result.ToArray(), n);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement