ellapt

T7.17.SubSetSumFixedLength

Jan 15th, 2013
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. using System;
  2.  
  3. class SubsSetSumFixedLength
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. long n;
  9. Console.WriteLine("Find if there exists a subset of array arrayOflongs /nwith sum S and count of elements k");
  10. do
  11. {
  12. Console.Write("Enter array length: ");
  13. }
  14. while (!(long.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  15.  
  16. long[] arrayOflongs = new long[n];
  17.  
  18. Console.WriteLine("Enter the elements of the array:");
  19. for (int i = 0; i < n; i++)
  20. {
  21. arrayOflongs[i] = long.Parse(Console.ReadLine());
  22. }
  23. Console.WriteLine("Enter the sum value:");
  24. long sum = long.Parse(Console.ReadLine());
  25. Console.WriteLine("Enter the length value:");
  26. long k = long.Parse(Console.ReadLine());
  27.  
  28. int cnt = 0; // count of subsets with the given sum
  29. string sbsetSum = ""; // the sum of the i-th subset prepared to be printed
  30. int sbsetSumsCnt = (int)Math.Pow(2, n) - 1; // max count of sbsetSums for this array
  31. Console.WriteLine("Subsets with sum of {0} : ", sum); // prepare for the output
  32. for (int i = 1; i <= sbsetSumsCnt; i++) //iteration through all possible subsets (excluding 0 subset)
  33. {
  34. sbsetSum = "";
  35. long tempSum = 0; // the sum of the i-th subset computed
  36. long kCnt = 0;
  37. for (int j = 0; j <= n; j++)
  38. {
  39. int mask = 1 << j; // the bit mask of the j-th element in the binary number
  40. int bit = (i & mask) >> j; // apply the mask to the i-th subset, then shift it to the rightmost (zero) position
  41. if (bit == 1) // check if the j-th element takes part in this subset (bit==1)
  42. {
  43. tempSum = tempSum + arrayOflongs[j]; // yes, add the j-th element to the computed subset sum
  44. sbsetSum = sbsetSum + " " + arrayOflongs[j]; // and prepare the output string
  45. kCnt++; // increment the current subset elements' count
  46. }
  47. }
  48. // all input array elements processed for the current subset, now check if their sum is equal to the given sum:
  49. if ((tempSum == sum) && (kCnt==k))
  50. {
  51. cnt++; // increment the count of the subsets satisfying the condition
  52. Console.WriteLine(" {0} ", sbsetSum); // print current subset
  53. }
  54. }
  55. Console.WriteLine("Count of subsets with the sum of {0}: {1}", sum, cnt); // print count of subsets with sum =orresponding bit given sum
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment