Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Generate random equation 2

Status
Not open for further replies.

MadCatmk2

Programmer
Oct 3, 2003
145
GB
Hi all

Was wondering if anyone has attempted to do something like this and could give me a starting point to attempt it.

I am looking into writing a program which takes a random selection of 6 numbers and generates an equation using all the number only once.

I can write the app so that it just reorganises the numbers and places a random char from +, -, *, / between each number which works.
What i am really looking for is some way of including parenthesis so that i can have functions that look like

Numbers: 1,2,3,4,2,2

1 + (2 * 3) - (4 /2) +2
or even
4 * ((2*3) / 2) + 2 - 1

Does anyone have any ideas how i could go about implementing this?

Thanks in advance
 
Try this.
___
[tt]
Private Sub Form_Load()
AutoRedraw = True
Randomize

Dim N As Long
For N = 1 To 5
Print MakeEquation
Next
End Sub

Function MakeEquation() As String
Dim N As Long, I As Long, X As Long, S As String
Dim Ops() As String, Nums(9) As Long
Ops = Split("+ - * /")

'randomize numbers
For N = 0 To 9
Nums(N) = N
Next
For N = 0 To 9
I = Int(10 * Rnd)
X = Nums(I)
Nums(I) = Nums(N)
Nums(N) = X
Next

'make equation
MakeEquation = Nums(0)
For N = 1 To 5
S = "X Op Y"
I = Int(Rnd + 0.5)
If N = 1 Or Rnd > 0.5 Then
S = Replace$(S, IIf(I, "X", "Y"), MakeEquation)
Else
S = Replace$(S, IIf(I, "X", "Y"), "(" & MakeEquation & ")")
End If
S = Replace$(S, "Op", Ops(Int(Rnd * 4)))
S = Replace$(S, IIf(I, "Y", "X"), Nums(N))
MakeEquation = S
Next
End Function[/tt]
___

Note that these equations are only syntactically correct. However, they may lead to fractional results or even division by zero error when evaluated.
 
That is superb mate. I can look into the division by zero part and fractional myself.

Thanks for your help (I'm now off to read this over and make sense of it).

Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top