Advertisement
Guest User

Untitled

a guest
Sep 29th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. static void Main()
  2. {
  3. var cnk = comb(new [] {1,2,3},2);
  4. foreach ( var c in cnk)
  5. {
  6. }
  7. }
  8.  
  9. public static IEnumerable<int[]> comb(int[] a, int k)
  10. {
  11. if (a == null || a.Length == 0 || k < 1 || k > a.Length)
  12. yield break;
  13.  
  14. int n = a.Length;
  15. // 1
  16. if ( k == 1)
  17. for ( int i = 0; i < n; i++)
  18. {
  19. yield return new int[] {a[i]};
  20. }
  21. else
  22. {
  23. // k
  24. for ( int i = 0; i < n - k + 1; i++)
  25. {
  26. var res = new int[k];
  27. for (int t = i, c = 0; t < i + k - 1; t++, c++)
  28. res[c] = a[t];
  29. for (int j = i + k - 1; j < n; j++)
  30. {
  31. res[k-1] = a[j];
  32. yield return res;
  33. }
  34. }
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement