Problem:
Insert + ,-,*,/ signs as necessary in the string 123456789 to form an expression that evaluates to a certain number.
Answer:
Sub test() getall 2009, 1 getall 2009, 2 End Sub Private Sub getall(ByVal theresult As Integer, Optional order As Byte = 1) Dim temp As Long, x(16) As String, op, i As Long, j As Long Dim out As String, all As Long, num As Integer num = 0 op = Array("+", "-", "*", "/", "") If order = 1 Then For i = 0 To 8 x(i * 2) = i + 1 Next ElseIf order = 2 Then For i = 0 To 8 x(i * 2) = 9 - i Next End If all = 5 ^ 8 - 1 For i = 0 To all temp = i For j = 1 To 8 x(j * 2 - 1) = op(temp Mod 5) temp = temp / 5 Next out = Replace(Join(x, ""), " ", "") If Evaluate(out) = theresult Then num = num + 1 Debug.Print "Solutions " & num & ":" & vbTab & out & "=" & theresult End If Next Debug.Print IIf(num, num, "No") & " solutions were found!" End Sub
It returns:
Solutions 1: 1*2345*6/7+8-9=2009
Solutions 2: 1/2*3*4*5*67+8-9=2009
Solutions 3: 1*2/3*45*67+8-9=2009
3 solutions were found!
Solutions 1: 9*8-7+6*54*3*2*1=2009
Solutions 2: 9+8*7+6*54*3*2*1=2009
Solutions 3: 9*8-7+6*54*3*2/1=2009
Solutions 4: 9+8*7+6*54*3*2/1=2009
4 solutions were found!