Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class NonSequentalSubsetSumSInIntArray
- {
- static void Main()
- {
- //* 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.
- //Example: arr={2, 1, 2, 4, 3, 5, 2, 6}, S=14 -> yes (1+2+5+6)
- int[] numbersArray = { 2, 1, 2, 4, 3, 5, 2, 6 };
- int sumS = 14;
- int numOfElements = numbersArray.Length,
- numOfSubsets = (int)Math.Pow(2, numOfElements) - 1;//The max possible subsets 2 to power of number of elements in the array
- int currentSum = 0,
- counter = 0;
- string currentSubset = "";
- List<string> subsetsWithSumS = new List<string>();
- for (int i = 1; i <= numOfSubsets; i++)
- {
- currentSubset = "";
- currentSum = 0;
- for (int j = 0; j < numOfElements; j++)
- {
- int mask = 1 << j,
- iAndMask = i & mask,
- bit = iAndMask >> j;
- if (bit==1)
- {
- currentSum += numbersArray[j];
- currentSubset += numbersArray[j] + " ";
- }
- }
- if (currentSum == sumS) //If we have found the wanted sum S
- {
- counter++; //Increase the counter
- subsetsWithSumS.Add(currentSubset);//Add the current subset to the list of subsets with sum S
- }
- }
- //Print the ouptput on the console
- if (counter == 0)//There are no subsets with sum S
- {
- Console.WriteLine("There are no subsets with sum {0}!", sumS);
- }
- else if (counter == 1)//There is only one subset with sum S
- {
- Console.WriteLine("There is one subset with sum {0}", sumS);
- Console.Write("{");
- Console.Write("{0}", subsetsWithSumS[0]);
- Console.WriteLine("}");
- }
- else//There are several subsets with SumS
- {
- Console.WriteLine("There are {0} subsets with sum {1}", counter,sumS);
- for (int i = 0; i < subsetsWithSumS.Count; i++)
- {
- Console.Write("{");
- Console.Write("{0}", subsetsWithSumS[i]);
- Console.WriteLine("}");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement