Advertisement
Nikolcho

Permutation PUB

Oct 4th, 2020 (edited)
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.27 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Exam
  6. {
  7.     class Program
  8.     {
  9.         static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
  10.         {
  11.             if (length == 1) return list.Select(t => new T[] { t });
  12.  
  13.             return GetPermutations(list, length - 1)
  14.                 .SelectMany(t => list.Where(e => !t.Contains(e)),
  15.                     (t1, t2) => t1.Concat(new T[] { t2 }));
  16.         }
  17.  
  18.  
  19.         static void Main()
  20.         {
  21.             int n = int.Parse(Console.ReadLine());
  22.  
  23.             IEnumerable<IEnumerable<int>> result =
  24.     GetPermutations(Enumerable.Range(1, n), n);
  25.  
  26.             var res = result.ToList();
  27.  
  28.             for (int i = 0; i < res.Count; i++)
  29.             {
  30.                 string output = string.Empty;
  31.                 int counter = 0;
  32.                 foreach (var item in res[i])
  33.                 {
  34.                     if (counter == res.Count - 1)
  35.                     {
  36.                         output += item;
  37.                     }
  38.                     else
  39.                     {
  40.                         output += item + " ";
  41.                     }
  42.                 }
  43.                 Console.WriteLine(output);
  44.             }
  45.         }
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement