Advertisement
Guest User

Untitled

a guest
Nov 21st, 2013
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. public class Program
  8. {
  9.     static void Main()
  10.     {
  11.        var result =  Combinations(new List<string> { "1", "2", "3", "4", "5" }, 5);
  12.  
  13.        foreach (var combination in result)
  14.        {
  15.            Console.WriteLine(combination);
  16.        }
  17.     }
  18.  
  19.     static IEnumerable<string> Combinations(List<string> characters, int length)
  20.     {
  21.         for (int i = 0; i < characters.Count; i++)
  22.         {
  23.             // ако листът има 1 елемент, алгоритъмът го връща
  24.             if (length == 1)
  25.                 yield return characters[i];
  26.             // генерира всички комбинации, без повторения    
  27.             else
  28.                 foreach (string next in Combinations(characters.GetRange(i + 1, characters.Count - (i + 1)), length - 1))
  29.                 {
  30.                     yield return characters[i] + next;
  31.                 }
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement