假設題目是:
A+2*B+3*C+4*D+5*E = 50
A+ B+ C+ D+ E = 13
A, B, C, D, E, 皆為正整數,這樣的狀況下去求解的話,
在 EXCEL 內,方程式應該怎麼寫才能把答案 SHOW 出來呢?
雖然答案不只一組,但是有兩個方程式做限制,還有設定並為正整數,
希望可以把所有符合的條件都列出。
Sub main()
Dim t1, t2, t3, t4, t5, irow As Integer
Dim totalCollection, hierarchyCollection As Variant
hierarchyCollection = Array(1, 2, 3, 4, 5)
totalCollection = Array(1, 1, 1, 1, 9)
irow = 1
For t1 = 1 To 9
totalCollection(0) = t1
For t2 = 1 To 9
totalCollection(1) = t2
For t3 = 1 To 9
totalCollection(2) = t3
For t4 = 1 To 9
totalCollection(3) = t4
For t5 = 1 To 9
totalCollection(4) = t5
If isEqual13(totalCollection) And isEqual50(totalCollection, hierarchyCollection) Then
writeToCell totalCollection, irow
irow = irow + 1
End If
Next
Next
Next
Next
Next
End Sub
Sub writeToCell(ByVal p_total As Variant, ByVal p_row As Integer)
Dim icol As Integer
icol = 1
For icol = 1 To 5
Cells(p_row, icol) = p_total(icol - 1)
Next
End Sub
Function isEqual50(ByVal p_total As Variant, ByVal p_hierarchy As Variant) As Boolean
Dim total As Integer
total = 0
For i = 0 To UBound(p_total)
total = total + p_total(i) * p_hierarchy(i)
Next
isEqual50 = IIf(total = 50, True, False)
End Function
Function isEqual13(ByVal p_total As Variant) As Boolean
Dim x, total As Integer
total = 0
For Each x In p_total
total = total + x
Next
isEqual13 = IIf(total = 13, True, False)
End Function