fork(11) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace PartitionTest {
  6. public static class Partitioning {
  7. public static IEnumerable<List<List<T>>> GetAllPartitions<T>(T[] elements, int maxlen) {
  8. if (maxlen<=0) {
  9. yield return new List<List<T>>();
  10. }
  11. else {
  12. T elem = elements[maxlen-1];
  13. var shorter=GetAllPartitions(elements,maxlen-1);
  14. foreach (var part in shorter) {
  15. foreach (var list in part.ToArray()) {
  16. list.Add(elem);
  17. yield return part;
  18. list.RemoveAt(list.Count-1);
  19. }
  20. var newlist=new List<T>();
  21. newlist.Add(elem);
  22. part.Add(newlist);
  23. yield return part;
  24. part.RemoveAt(part.Count-1);
  25. }
  26. }
  27. }
  28.  
  29. public static void Main()
  30. {
  31. foreach(var part in Partitioning.GetAllPartitions(new[] { 1, 2, 3, 4 },4)) {
  32. Console.WriteLine(string.Join(",",part.Select(x => "("+string.Join(",",x)+")")));
  33. }
  34. }
  35. }
  36. }
Success #stdin #stdout 0.01s 29808KB
stdin
Standard input is empty
stdout
(1,2,3,4)
(1,2,3),(4)
(1,2,4),(3)
(1,2),(3,4)
(1,2),(3),(4)
(1,3,4),(2)
(1,3),(2,4)
(1,3),(2),(4)
(1,4),(2,3)
(1),(2,3,4)
(1),(2,3),(4)
(1,4),(2),(3)
(1),(2,4),(3)
(1),(2),(3,4)
(1),(2),(3),(4)