Cybercrux

Everything is achievable through technology

Find all subsets of an int array whose sums equal a given target

Leave a comment

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessRule
{
static class Program
{
static int TargetSum = 2;
static int[] InputData = new[] { 1, 2, 4, 8, 16, 32, 64};

static void Main()
{
GetCombinations(InputData, TargetSum).ToList().ForEach(x => Console.WriteLine(x));

Console.ReadKey();
}
public static IEnumerable<string> GetCombinations(int[] set, int sum, string values=””)
{
for (int i = 0; i < set.Length; i++)
{
int left = sum – set[i];
string vals = set[i] + “,” + values;
if (left == 0)
{
yield return vals;
}
else
{
int[] possible = set.Take(i).Where(n => n <= sum).ToArray();
if (possible.Length > 0)
{
foreach (string s in GetCombinations(possible, left, vals))
{
yield return s;
}
}
}
}
}

}
}

Advertisements

Author: nikhilsreeni

Software engineer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s