ellapt

T7.16.SubsetWithSumS

Jan 15th, 2013
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. using System;
  2.  
  3. class SubsetWithSumS
  4. {
  5. static void Main()
  6. {
  7. string inputVar;
  8. long n;
  9. Console.WriteLine("Find if there exists a subset of array arrayOflongs with sum S");
  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. int cnt = 0; // count of subsets with the given sum
  26. string sbsetSum = ""; // the sum of the i-th subset prepared to be printed
  27. int sbsetSumsCnt = (int)Math.Pow(2, n) - 1; // max count of sbsetSums for this array
  28. Console.WriteLine("Subsets with sum of {0} : ", sum); // prepare for the output
  29. for (int i = 1; i <= sbsetSumsCnt; i++) //iteration through all possible subsets (excluding 0 subset)
  30. {
  31. sbsetSum = "";
  32. long tempSum = 0; // the sum of the i-th subset computed
  33. for (int j = 0; j <= n; j++)
  34. {
  35. int mask = 1 << j; // the bit mask of the j-th element in the binary number
  36. int bit = (i & mask) >> j; // apply the mask to the i-th subset, then shift it to the rightmost (zero) position
  37. if (bit == 1) // check if the j-th element takes part in this subset (bit==1)
  38. {
  39. tempSum = tempSum + arrayOflongs[j]; // yes, add the j-th element to the computed subset sum
  40. sbsetSum = sbsetSum + " " + arrayOflongs[j]; // and prepare the output string
  41. }
  42. }
  43. // all input array elements processed for the current subset, now check if their sum is equal to the given sum:
  44. if (tempSum == sum)
  45. {
  46. cnt++; // increment the count of the subsets satisfying the condition
  47. Console.WriteLine(" {0} ", sbsetSum); // print current subset
  48. }
  49. }
  50. Console.WriteLine("Count of subsets with the sum of {0}: {1}", sum,cnt); // print count of subsets with sum =orresponding bit given sum
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment