Advertisement
Guest User

Untitled

a guest
Dec 20th, 2013
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. /*16. * We are given an array of integers and a number S.
  2. Write a program to find if there exists a subset of the elements of the array that has a sum S.
  3. Example: arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14  yes (1+2+5+6)*/
  4.  
  5. using System;
  6.  
  7. class FindSubsetSum
  8. {
  9.     static void Main()
  10.     {
  11.         int lengthOfArray = 10;
  12.         int[] numbers = { 1, 5, 3, 2, 8, -2, 4, -1, 9, -5 };
  13.  
  14.         //Console.Write("Enter the length of array: ");
  15.         //int lengthOfArray = int.Parse(Console.ReadLine());
  16.        
  17.         //int[] numbers = new int[lengthOfArray];
  18.         //for (int i = 0; i < lengthOfArray; i++)
  19.         //{
  20.         //    numbers[i] = int.Parse(Console.ReadLine());
  21.         //}
  22.                
  23.         Console.Write("Enter the value of the sum which we looking for: ");
  24.         int sum = int.Parse(Console.ReadLine());
  25.  
  26.         int variation = (int)Math.Pow(2, lengthOfArray) - 1;
  27.         int counter = 0;
  28.         bool isConsist = false;
  29.  
  30.         for (int i = 1; i <= variation; i++)
  31.         {
  32.             string binaryI = Convert.ToString(i, 2).PadLeft(lengthOfArray, '0');
  33.             long result = 0;
  34.             string strResult = string.Empty;
  35.  
  36.             for (int j = 0; j < lengthOfArray; j++)
  37.             {
  38.                 if (binaryI[j] == '1')
  39.                 {
  40.                     result += numbers[j];
  41.                     strResult += numbers[j] + " + ";
  42.                 }
  43.             }
  44.            
  45.             if (result == sum)
  46.             {
  47.                 isConsist = true;
  48.                 strResult = strResult.Remove(strResult.Length - 3);
  49.                 Console.WriteLine("[{0}], S = {1}  yes ({2})", string.Join(", ", numbers), sum, strResult);
  50.                 counter++;
  51.             }
  52.         }
  53.  
  54.         if (isConsist)
  55.         {
  56.             Console.WriteLine("Total: {0}", counter);
  57.         }
  58.         else
  59.         {
  60.             Console.WriteLine("[{0}], S = {1}  no", string.Join(", ", numbers), sum);  
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement