ellapt

T7.21.CombinationsOfInts

Jan 17th, 2013
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. using System;
  2.  
  3. class CombinationsOfInts
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. int n, k;
  9. Console.WriteLine(" Read numbers N and K,\n generate all combinations of K distinct elements from the set [1..N]. ");
  10. do
  11. {
  12. Console.Write("Enter array length N: ");
  13. }
  14. while (!(int.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  15. do
  16. {
  17. Console.Write("Enter combination length K: ");
  18. }
  19. while (!(int.TryParse(inputVar = Console.ReadLine(), out k)) || k == 0 || k > n);
  20.  
  21. int[] arrayOfints = new int[k];
  22. Combination(arrayOfints, n, 0, 0); ;
  23. }
  24.  
  25. static void PrintResult(int[] array)
  26. {
  27. int n = array.Length;
  28. for (int i = 0; i < n; i++)
  29. {
  30. Console.Write(array[i] + 1 + (i == n - 1 ? "\n" : " "));
  31. }
  32. }
  33.  
  34. static void Combination(int[] resArr, int n, int combIndex,int goNext)
  35. {
  36. if (combIndex == resArr.Length)
  37. {
  38. PrintResult(resArr);
  39. return;
  40. }
  41.  
  42. for (int j = goNext; j < n; j++)
  43. {
  44. resArr[combIndex] = j;
  45. Combination(resArr, n, combIndex + 1, j+1);
  46. }
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment