Advertisement
Hristo_B

SubsetSum

Jun 13th, 2013
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class ChecksIfSumIsZero
  6. {
  7.     static void Main()
  8.     {
  9.         //We are given 5 integer numbers. Write a program that checks if the sum of some subset of them is 0.
  10.         //Example: 3, -2, 1, 1, 8  1+1-2=0.
  11.  
  12.         Console.Write("Insert the first number: ");
  13.         int firstNumber = int.Parse(Console.ReadLine());
  14.         Console.Write("Insert the second number: ");
  15.         int secondNumber = int.Parse(Console.ReadLine());
  16.         Console.Write("Insert the third number: ");
  17.         int thirdNumber = int.Parse(Console.ReadLine());
  18.         Console.Write("Insert the forth number: ");
  19.         int forthNumber = int.Parse(Console.ReadLine());
  20.         Console.Write("Insert the fifth number: ");
  21.         int fifthNumber = int.Parse(Console.ReadLine());
  22.  
  23.  
  24.         int[] array = new int[] { firstNumber, secondNumber, thirdNumber, forthNumber, fifthNumber };
  25.  
  26.  
  27.         for (int index = 0; index < 32; index++) // 31 are all the possible variations to sum the numbers
  28.         {
  29.             int sum = 0;
  30.  
  31.             List<int> arrayPossitons = new List<int>(); //here I save the positions of the numbers which sum is 0
  32.  
  33.             for (int i = 0; i < 5; i++)
  34.             {
  35.  
  36.                 if ((1 << i & index) != 0)
  37.                 {
  38.                     arrayPossitons.Add(array[i]);
  39.                 }
  40.             }
  41.  
  42.             if (arrayPossitons.Sum() == 0 && arrayPossitons.Count!=0) //checks if there is sum = 0 and the array is not empty
  43.             {
  44.                 Console.WriteLine("yes there is");
  45.                 for (int j = 0; j < arrayPossitons.Count; j++)
  46.                 {
  47.                     Console.Write("{0} ", arrayPossitons[j]);
  48.                 }
  49.                 Console.WriteLine();
  50.             }
  51.         }
  52.  
  53.        
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement