0

I want to generate random mathematical expressions in c# like.

2*3-6         
2(85+96)*12-96       
78/8-9
... etc

please help me in this.

Lrrr
  • 4,755
  • 5
  • 41
  • 63
Rajan Verma - Aarvy
  • 1,969
  • 18
  • 20
  • 1
    You will need to be more restrictive. What rules should the expressions follow (what operations?, how many operants?, what range are the values?, integers only?) And what do you consider random? Do you want to draw one expression uniformly at random from the set of all allowed expressions? Or should it just "look random"? – Vincent van der Weele Mar 04 '15 at 07:21

1 Answers1

4

There is no GetMeRandomMathExpression in C# (or any language as far as I know) but you could generate random expression like this:

  • Put all operands in switch case

  • Use random to decide how many operands are in your expression I name it K.

  • Use random K times and the switch case in first step to find all the operands randomly.

  • Use random K+1 times to find K+1 number that you need in your formula.

like 462*823-61-263+518*490*479+851+276+13-208-418-537+486+476+15*227-274 is a random expression that I generate with my simple code :

using System;
using System.Text;

public class Test
{
    public static void Main()
    {
        Random r = new Random();
        StringBuilder builder= new StringBuilder();


        int numOfOperand = r.Next(1, 20); // it is just a test so I just want to have up to 20 operands.
        int randomNumber;
        for(int i = 0 ; i<numOfOperand ; i++){

            randomNumber = r.Next(1, 1000);
            builder.Append(randomNumber);


            int randomOperand = r.Next(1, 4);

            string operand = null;

            switch (randomOperand)
            {
                case 1:
                    operand = "+";
                break;
                case 2:
                    operand = "-";
                break;
                case 3:
                    operand = "*";
                break;
                case 4:
                    operand = "/";
                break;
            }
            builder.Append(operand);
        }
        randomNumber = r.Next(1, 1000);
            builder.Append(randomNumber);

        Console.WriteLine(builder.ToString());
    }
}

You could find online version here

Lrrr
  • 4,755
  • 5
  • 41
  • 63