实现一个递归程序,显示所有操作符的组合以达到给定的总和。

huangapple go评论88阅读模式
英文:

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

问题

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Generate(int n, int x, int currentIndex, int result, string expression, ref bool counter)
        {
            if (currentIndex == n + 1)
            {
                if (result == x)
                {
                    Console.WriteLine(expression + " = " + x);
                    counter = true;
                }

                return;
            }

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

        static void Main()
        {
            int n = Convert.ToInt32(Console.ReadLine());
            int x = Convert.ToInt32(Console.ReadLine());
            bool counter = false;

            Generate(n, x, 2, 1, "1", ref counter);

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

            Console.ReadLine();
        }
    }
}

请注意,我已经将counter参数传递给Generate函数,并在符合条件时将其设置为true,以便在达到目标值时跟踪可能性,并且不再使用静态字段。

英文:
  • 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.

答案1

得分: 0

这是我会做的方式。将二进制中的0视为减法,将1视为加法:

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

    Console.Write("输入一个值作为 'n' [n >= 2]: ");
    response1 = Console.ReadLine();
    Console.Write("输入一个值作为 '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'必须大于或等于2。");
        }
    }
    else
    {
        Console.WriteLine("无效的 'n' 或 'x' 值!");
    }

    Console.WriteLine("按Enter键退出。");
    Console.ReadLine();
}

输出:

输入一个值作为 'n' [n >= 2]: 6
输入一个值作为 'x': 3
1 - 2 - 3 - 4 + 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 + 2 + 3 - 4 - 5 + 6 = 3
按Enter键退出。
英文:

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(&quot;Enter a value for &#39;n&#39; [n&gt;=2]: &quot;);
        response1 = Console.ReadLine();
        Console.Write(&quot;Enter a value for &#39;x&#39;: &quot;);
        response2 = Console.ReadLine();

        if (int.TryParse(response1, out n) &amp;&amp; int.TryParse(response2, out x))
        {
            if (n &gt;= 2)
            {
                List&lt;String&gt; solutions = new List&lt;string&gt;();
                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 &lt; max; i++)
                {
                    int sum = numbers[0];
                    String binary = Convert.ToString(i, 2).PadLeft(width, &#39;0&#39;);
                    String equation = numbers[0].ToString();
                    for(int d=0; d&lt;binary.Length; d++)
                    {
                        char operation = binary[d];
                        equation = equation + ((operation == &#39;0&#39;) ? &quot; - &quot; : &quot; + &quot;) + numbers[d + 1];
                        sum = sum + ((operation == &#39;0&#39;) ? -1 : 1) * numbers[d + 1];
                    }
                    equation = equation + &quot; = &quot; + sum;
                    if (sum == x)
                    {
                        solutions.Add(equation);
                    }
                }
                if (solutions.Count == 0)
                {
                    Console.WriteLine(&quot;N/A&quot;);
                }
                else
                {
                    foreach(String solution in solutions)
                    {
                        Console.WriteLine(solution);
                    }
                }
            }
            else
            {
                Console.WriteLine(&quot;&#39;n&#39; must be greater than or equal to 2.&quot;);
            }
        }
        else
        {
            Console.WriteLine(&quot;Invalid value for &#39;n&#39; or &#39;x&#39;!&quot;);
        }

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

Output:

Enter a value for &#39;n&#39; [n&gt;=2]: 6
Enter a value for &#39;x&#39;: 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.

huangapple
  • 本文由 发表于 2023年1月8日 23:52:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定