上次是将所有结果计算后列表,再查找24。这次是用递归全排列作大循环,大循环内再考虑3个运算符优先权算24。还是没考虑重复的情况。
程序代码:
Option Explicit
Private Sub Command1_Click()
Dim arr(1 To 4) As Single
Dim temp() As String
Dim i As Integer
List1.Clear
temp = Split(Text1.Text, " ") '注1<得到4个操作数,赋值到arr中.
For i = 0 To UBound(temp)
arr(i + 1) = Val(temp(i))
Next '>注1
permutation arr, 1, 4
End Sub
Sub permutation(a() As Single, m As Integer, n As Integer)
Dim i As Integer
Dim temp As Integer
Dim operator1 As Byte
Dim operator2 As Byte
Dim operator3 As Byte
If m = n Then '注2:判断当前排列是否完成.
For operator1 = 0 To 3 '注3<三重循环得到3个操作符的全排列.
For operator2 = 0 To 3
For operator3 = 0 To 3
'注4:判断操作符的各种估先权组合得到地计算结果是否为24
'5种操作符优先权顺序是: 1 2 3,1 3 2,2 1 3,2 3 1 ,3 2 1.(3 1 2 等同于1 3 2)
If operate(operator3, operate(operator2, operate(operator1, a(1), a(2)), a(3)), a(4)) = 24 Then
List1.AddItem "((" & a(1) & convert(operator1) & a(2) & ")" & convert(operator2) & a(3) & ")" & convert(operator3) & a(4)
End If
If operate(operator2, operate(operator1, a(1), a(2)), operate(operator3, a(3), a(4))) = 24 Then
List1.AddItem "(" & a(1) & convert(operator1) & a(2) & ")" & convert(operator2) & "(" & a(3) & convert(operator3) & a(4) & ")"
End If
If operate(operator3, operate(operator1, a(1), operate(operator2, a(2), a(3))), a(4)) = 24 Then
List1.AddItem "(" & a(1) & convert(operator1) & "(" & a(2) & convert(operator2) & a(3) & "))" & convert(operator3) & a(4)
End If
If operate(operator1, a(1), operate(operator3, operate(operator2, a(2), a(3)), a(4))) = 24 Then
List1.AddItem a(1) & convert(operator1) & "((" & a(2) & convert(operator2) & a(3) & ")" & convert(operator3) & a(4) & ")"
End If
If operate(operator1, a(1), operate(operator2, a(2), operate(operator3, a(3), a(4)))) = 24 Then
List1.AddItem a(1) & convert(operator1) & "(" & a(2) & convert(operator2) & "(" & a(3) & convert(operator3) & a(4) & "))"
End If
Next
Next
Next '>注3
Exit Sub
Else
For i = m To n '注5<得到a()全排列
swap a(m), a(i)
permutation a(), m + 1, n
swap a(m), a(i)
Next '>注5
End If
End Sub
Sub swap(a1 As Single, b1 As Single)
Dim temp As Single
temp = a1
a1 = b1
b1 = temp
End Sub
Function operate(i As Byte, x As Single, y As Single) As Single '按操作符索引号得到2个操作数的计算结果.注意顺序无误.
Select Case i
Case Is = 0
operate = x + y
Case Is = 1
operate = x - y
Case Is = 2
operate = x * y
Case Is = 3
If y = 0 Then
operate = 99.9
Else
operate = x / y
End If
End Select
End Function
Function convert(i As Byte) As String '按操作符索引转化为"+-*/"
Select Case i
Case Is = 0
convert = "+"
Case Is = 1
convert = "-"
Case Is = 2
convert = "*"
Case Is = 3
convert = "/"
End Select
End Function
如果把注3对应的内容删掉换成显示a(1)-a(4)就能看到遍历效果了.
[
本帖最后由 lianyicq 于 2015-6-18 12:10 编辑 ]