Advertisement
sylviapsh

Non-Sequental Subset with SumS In Int Array

Jan 12th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class NonSequentalSubsetSumSInIntArray
  6. {
  7.   static void Main()
  8.   {
  9.     //* We are given an array of integers and a number S. Write a program to find if there exists a subset of the elements of the array that has a sum S.
  10.     //Example: arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14 -> yes (1+2+5+6)
  11.  
  12.     int[] numbersArray = { 2, 1, 2, 4, 3, 5, 2, 6 };
  13.     int sumS = 14;
  14.    
  15.     int numOfElements = numbersArray.Length,
  16.         numOfSubsets = (int)Math.Pow(2, numOfElements) - 1;//The max possible subsets 2 to power of number of elements in the array
  17.  
  18.     int currentSum = 0,
  19.         counter = 0;
  20.     string currentSubset = "";
  21.     List<string> subsetsWithSumS = new List<string>();
  22.  
  23.     for (int i = 1; i <= numOfSubsets; i++)
  24.     {
  25.       currentSubset = "";
  26.       currentSum = 0;
  27.       for (int j = 0; j < numOfElements; j++)
  28.       {
  29.         int mask = 1 << j,
  30.             iAndMask = i & mask,
  31.             bit = iAndMask >> j;
  32.  
  33.         if (bit==1)
  34.         {
  35.           currentSum += numbersArray[j];
  36.           currentSubset += numbersArray[j] + " ";
  37.         }
  38.       }
  39.  
  40.       if (currentSum == sumS) //If we have found the wanted sum S
  41.       {
  42.         counter++; //Increase the counter
  43.         subsetsWithSumS.Add(currentSubset);//Add the current subset to the list of subsets with sum S
  44.       }
  45.     }
  46.  
  47.     //Print the ouptput on the console
  48.     if (counter == 0)//There are no subsets with sum S
  49.     {
  50.       Console.WriteLine("There are no subsets with sum {0}!", sumS);
  51.     }
  52.     else if (counter == 1)//There is only one subset with sum S
  53.     {
  54.       Console.WriteLine("There is one subset with sum {0}", sumS);
  55.       Console.Write("{");
  56.       Console.Write("{0}", subsetsWithSumS[0]);
  57.       Console.WriteLine("}");
  58.     }
  59.     else//There are several subsets with SumS
  60.     {
  61.       Console.WriteLine("There are {0} subsets with sum {1}", counter,sumS);
  62.      
  63.       for (int i = 0; i < subsetsWithSumS.Count; i++)
  64.       {
  65.         Console.Write("{");
  66.         Console.Write("{0}", subsetsWithSumS[i]);
  67.         Console.WriteLine("}");
  68.       }
  69.     }
  70.   }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement