Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace ZeroSubsets
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter numbers count:");
- int numberCount = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter subset sum:");
- int subsetSum = int.Parse(Console.ReadLine());
- int[] numbersArray = new int[numberCount];
- for (int i = 0; i < numberCount; i++)
- {
- numbersArray[i] = int.Parse(Console.ReadLine());
- }
- int iterations = (1 << numberCount) - 1;
- int bitMask = 0;
- bool noZeroSubset = true;
- int currentSum = 0;
- for (int i = 1; i < iterations; i++)
- {
- bitMask = i;
- currentSum = 0;
- int j = 0;
- int index = 0;
- string[] sumText = new string[numberCount];
- while (j < numberCount)
- {
- if ((bitMask & 1) == 1)
- {
- currentSum += numbersArray[j];
- sumText[index] = numbersArray[j].ToString();
- index++;
- }
- bitMask = bitMask >> 1;
- j++;
- }
- if (currentSum == subsetSum)
- {
- noZeroSubset = false;
- foreach (var number in sumText)
- {
- Console.Write(number + "+");
- }
- Console.Write("={0}", subsetSum);
- Console.WriteLine();
- }
- }
- if (noZeroSubset)
- {
- Console.WriteLine("No zero subset");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement