自动随机向数学运算字符串添加括号



您有任何想法自动随机地在数学运算字符串中添加括号吗?

例如。

给定的操作字符串:

57 x 40 - 14 + 84 ÷ 19

我需要在上面的字符串中随机自动添加括号。

所以它变成了:

(57 x 40) - 14 + (84 ÷ 19) 或

(57 x 40) - (14 + 84 ÷ 19) 或

57 x (40 - 14) + (84 ÷ 19) 或

57 x (40 - 14 + 84 ÷ 19) 或

57 x (40 - (14 + 84) ÷ 19)

真的很感谢帮助!!

米克

我假设了三件事:

  1. 数字和运算符之间始终有空格字符
  2. 所有数字都是整数(您可以轻松地将其更改为其他类型的数字)
  3. 所有不是数字的东西都是运算符

C# 中的示例:

Math m = new Math(); 
string p = m.DoStuff("57 x 40 - 14 + 84 ÷ 19");
Console.WriteLine(p);
class Math
{       
    internal string DoStuff(string p)
    {
        bool isParOpen = false;
        Random rnd = new Random();
        StringBuilder result = new StringBuilder();
        int i;
        string[] stack = p.Split(' ');
        foreach (var item in stack)
        {
            if (int.TryParse(item, out i))
            {
                if (rnd.Next(2) == 1)
                {
                    result.Append(isParOpen ? string.Format("{0}) ", item) : string.Format("({0} ", item));
                    isParOpen = !isParOpen;
                }
                else
                {
                    result.Append(item).Append(" ");
                }
            }
            else
            {
                result.Append(item).Append(" ");
            }
        }
        if (isParOpen)
        {
            result.Append(")");
        }
        return result.ToString();
    }
}

如果将数学表达式作为字符串处理,则可以随机添加括号(例如,向字符串添加随机字符),然后使用脚本引擎,可以评估表达式。

最新更新