Summation of different combinations

You have a string of digits say 123. You can insert a + or – sign in front of every digit. Find all of the different possibilities and return the sum of all results.

For example:
+1+2+3 = 6
+12+3 = 15
+123 = 123
+1+23 = 24

-1-2-3 = 6

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

namespace ConsoleApplication1
{
    class Program
    {
        public static int sum = 0;
        static void Main(string[] args)
        {
            string str = "123";
            GenerateCombinations(str, 0, "", "");
            Console.WriteLine("Total Sum = " + sum);
        }

        public static void GenerateCombinations(string str, int startPos, string tempStrWithoutSymbol, string tempStrWithSymbol)
        {
            if (tempStrWithoutSymbol == str)
            {
                Console.WriteLine(tempStrWithSymbol + " = " + Calculate(tempStrWithSymbol));
                sum = sum + Calculate(tempStrWithSymbol);
            }

            else
            {
                for (int len = 1; len <= str.Length - startPos; len++)
                {
                    GenerateCombinations(str, startPos + len, tempStrWithoutSymbol + str.Substring(startPos, len), tempStrWithSymbol + "+" + str.Substring(startPos, len));
                    GenerateCombinations(str, startPos + len, tempStrWithoutSymbol + str.Substring(startPos, len), tempStrWithSymbol + "-" + str.Substring(startPos, len));
                }
            }
        }

        public static int Calculate(string strExp)
        {
            DataTable dt = new DataTable();
            return ((int)dt.Compute(strExp, ""));
        }
    }
}

Output
=======
+1+2+3 = 6
+1+2-3 = 0
+1-2+3 = 2
+1-2-3 = -4
+1+23 = 24
+1-23 = -22
-1+2+3 = 4
-1+2-3 = -2
-1-2+3 = 0
-1-2-3 = -6
-1+23 = 22
-1-23 = -24
+12+3 = 15
+12-3 = 9
-12+3 = -9
-12-3 = -15
+123 = 123
-123 = -123
Total Sum = 0
Press any key to continue . . .
Advertisements
This entry was posted in Information Technology. Bookmark the permalink.

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