Rajan Verma - Aarvy
Rajan Verma - Aarvy

Reputation: 2117

Is there any way to generate random mathematical expressions in c#?

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.

Upvotes: 0

Views: 3460

Answers (1)

Lrrr
Lrrr

Reputation: 4805

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

Upvotes: 4

Related Questions