Advertisement
svetoslavhl

Untitled

May 21st, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. //17.*Write a program that reads three integer numbers N, K and S and an array of N elements from the console.
  2. // Find in the array a subset of K elements that have sum S or indicate about its absence.
  3.  
  4. using System;
  5.  
  6. class SubsetSumSOfKElements
  7. {
  8. static void Main()
  9. {
  10. //reading the input data from the console
  11. int sumS;
  12. do
  13. {
  14. Console.Write("Please enter the given sum: ");
  15. }
  16. while (!int.TryParse(Console.ReadLine(), out sumS));
  17.  
  18. uint kElements;
  19. do
  20. {
  21. Console.Write("Please enter the count of elements: ");
  22. }
  23. while (!uint.TryParse(Console.ReadLine(), out kElements));
  24.  
  25. uint numbersN;
  26. do
  27. {
  28. Console.Write("Please enter the size of array: ");
  29. }
  30. while (!uint.TryParse(Console.ReadLine(), out numbersN));
  31.  
  32. int[] array = new int[numbersN];
  33. for (int i = 0; i < numbersN; i++)
  34. {
  35. do
  36. {
  37. Console.Write("Please enter element {0} of array: ", i + 1);
  38. }
  39. while (!int.TryParse(Console.ReadLine(), out array[i]));
  40. }
  41.  
  42. string subset = string.Empty;
  43. bool haveGivenSum = false;
  44.  
  45. // solution with bitwise operations
  46. // combinations are equal the number of elements per square
  47. // We present each number as a bit position in the binary number
  48. // This cycle checks all possible combinations
  49. int maxSubsets = (int)Math.Pow(2, numbersN);
  50. for (int i = 1; i < maxSubsets; i++)
  51. {
  52. subset = string.Empty;
  53. int checkingSum = 0;
  54. int counter = 0;
  55. for (int j = 0; j < array.Length; j++)
  56. {
  57. int mask = 1 << j;
  58. int nAndMask = i & mask;
  59. int bit = nAndMask >> j;
  60. if (bit == 1)
  61. {
  62. checkingSum = checkingSum + array[j];
  63. if (array[j] < 0 || subset == "")
  64. {
  65. subset = subset + array[j];
  66. counter++;
  67. }
  68. else
  69. {
  70. subset = subset + "+" + array[j];
  71. counter++;
  72. }
  73. }
  74. }
  75. if (checkingSum == sumS && counter == kElements)
  76. {
  77. Console.WriteLine("Subset sum {0} of {1} elements is {2}", sumS, kElements, subset);
  78. haveGivenSum = true;
  79. }
  80. }
  81. if (!haveGivenSum)
  82. {
  83. Console.WriteLine("No sequence of {0} elements with the given sum", kElements);
  84. }
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement