Home > other >  Implement a recursive program that displays all combinations of operators to reach a given sum
Implement a recursive program that displays all combinations of operators to reach a given sum

Time:01-09

  • I have to write a program that displays all the combinations of operators( and -), to put between numbers from 1 to N (N>=2), in order to reach a targeted value X. It should write "N/A" if there is no possibility.

For the input:

  • n=6
  • x=3

It displays:

  • 1 2 3 - 4 - 5 6 = 3
  • 1 2 - 3 4 5 - 6 = 3
  • 1 - 2 - 3 - 4 5 6 = 3
using System;

namespace ConsoleApp1
{
    class Program
    {
       static bool counter;

       static void Generate(int n, int x, int currentIndex, int result, string expression)
        {
            counter = true;

            if (currentIndex == n   1)
            {
                if (result == x)
                {
                    Console.WriteLine(expression   " = "   x);
                }

                return;
            }

            Generate(n, x, currentIndex   1, result   currentIndex, expression   "   "   currentIndex);
            Generate(n, x, currentIndex   1, result - currentIndex, expression   " - "   currentIndex);
        }

       static void Main()
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int x = Convert.ToInt32(Console.ReadLine());
            const int doi = 2;

            Generate(n, x, doi, 1, "1");

            if (!counter)
            {
                Console.WriteLine("N/A");
            }

            Console.ReadLine();
        }
    }
}
 It gives me the error : JRM003 (Error) : Don't use static fields. (line: 7, character: 7).

Where can I place the "counter" in order to track if there is possibility of reaching to the targeted value, and get rid of the error.

CodePudding user response:

The best thing to do is to use ref:

using System;

namespace ConsoleApp1
{
    class Program
    {
      
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int x = Convert.ToInt32(Console.ReadLine());
            const int doi = 2;

            bool counter = false;
            Generate(n, x, doi, 1, "1", ref counter);

            if (!counter)
            {
                Console.WriteLine("N/A");
            }

            Console.ReadLine();
        }
        
        static void Generate(int n, int x, int currentIndex, int result, string expression, ref bool counter)
        {
            counter = true;

            if (currentIndex == n   1)
            {
                if (result == x)
                {
                    Console.WriteLine(expression   " = "   x);
                }

                return;
            }

            Generate(n, x, currentIndex   1, result   currentIndex, expression   "   "   currentIndex, ref counter);
            Generate(n, x, currentIndex   1, result - currentIndex, expression   " - "   currentIndex, ref counter);
        }
    }
}

CodePudding user response:

Here's how I'd do it. Count in binary treating 0 as subtraction and 1 as addition:

    public static void Main(string[] args)
    {
        int n, x;
        String response1, response2;

        Console.Write("Enter a value for 'n' [n>=2]: ");
        response1 = Console.ReadLine();
        Console.Write("Enter a value for 'x': ");
        response2 = Console.ReadLine();

        if (int.TryParse(response1, out n) && int.TryParse(response2, out x))
        {
            if (n >= 2)
            {
                List<String> solutions = new List<string>();
                int[] numbers = Enumerable.Range(1, n).ToArray();
                int width = numbers.Length - 1;
                int max = (int)Math.Pow(2, numbers.Length - 1);
                for(int i=0; i < max; i  )
                {
                    int sum = numbers[0];
                    String binary = Convert.ToString(i, 2).PadLeft(width, '0');
                    String equation = numbers[0].ToString();
                    for(int d=0; d<binary.Length; d  )
                    {
                        char operation = binary[d];
                        equation = equation   ((operation == '0') ? " - " : "   ")   numbers[d   1];
                        sum = sum   ((operation == '0') ? -1 : 1) * numbers[d   1];
                    }
                    equation = equation   " = "   sum;
                    if (sum == x)
                    {
                        solutions.Add(equation);
                    }
                }
                if (solutions.Count == 0)
                {
                    Console.WriteLine("N/A");
                }
                else
                {
                    foreach(String solution in solutions)
                    {
                        Console.WriteLine(solution);
                    }
                }
            }
            else
            {
                Console.WriteLine("'n' must be greater than or equal to 2.");
            }
        }
        else
        {
            Console.WriteLine("Invalid value for 'n' or 'x'!");
        }

        Console.WriteLine("Press Enter to Quit.");
        Console.ReadLine();
    }

Output:

Enter a value for 'n' [n>=2]: 6
Enter a value for 'x': 3
1 - 2 - 3 - 4   5   6 = 3
1   2 - 3   4   5 - 6 = 3
1   2   3 - 4 - 5   6 = 3
Press Enter to Quit.
  • Related