0

Do you have any idea to add parentheses to math operation string automatically and randomly?

For example.

A given operation string:

57 x 40 - 14 + 84 ÷ 19

I need to auto add parentheses randomly in above string.

so it becomes:

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

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

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

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

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

It really appreciated for the help!!

Mick,

Mick
  • 3
  • 1
  • 4
    Which programming language, what have you tried, etc. – Sjoerd May 14 '12 at 12:36
  • Select an operator at random, move left and right until you've got a random number of numbers. Repeat at random. What's the problem ? – High Performance Mark May 14 '12 at 12:38
  • Have you considered the alternative of picking each pair of numbers and doing each operation on them to produce 4 sets of n-1 numbers and repeating that until you have all possible results? Or do you actually need to have each of the possible strings with parenthesis? – Helen May 14 '12 at 12:59

2 Answers2

1

I assumed three things:

  1. There is always space char between number and operator
  2. All numbers are integers (you can easily change that to other types)
  3. Everything that is not number is operator

Example in 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();
    }
}
Tschareck
  • 4,071
  • 9
  • 47
  • 74
0

If you handle the mathematical expresion as a String, you can add parenthesis randomly (Eg. add random chars to a string), and then using an script engine, you can evaluate the expresion.

Community
  • 1
  • 1
Oscar Castiblanco
  • 1,626
  • 14
  • 31