網路城邦
回本城市首頁 唐老鴨之家
市長:  副市長:
加入本城市推薦本城市加入我的最愛訂閱最新文章
udn城市資訊科技網路分享【唐老鴨之家】城市/討論區/
討論區Excel VBA 字體:
上一個討論主題 回文章列表 下一個討論主題
益智問題求解之二
 瀏覽371|回應0推薦0


等級:6
留言加入好友
 □□□
+□□□
─────
 □□□

□中填入1,2,3,...,9,不可重複,可知答案為何? (有336組解答,例如124,659,783是其中一組)

基本求解版(較慢)

Dim selected(10) As Boolean
Private Sub CommandButton1_Click()
h = 1
For i = 123 To 987
For j = 123 To 987
For k = 123 To 987
For c = 1 To 9
selected(c) = False
Next c
If k = i + j And check(i) And check(j) And check(k) Then
Cells(h, 1) = i
Cells(h, 2) = j
Cells(h, 3) = k
h = h + 1
End If
Next k
Next j
Next i
End Sub

Function check(a)
a1 = Int(a / 100)
a2 = Int((a Mod 100) / 10)
a3 = a - 100 * a1 - 10 * a2
If selected(a1) Then
check = False
Else
selected(a1) = True
If selected(a2) Then
check = False
Else
selected(a2) = True
If selected(a3) Then
check = False
Else
selected(a3) = True
check = True
End If
End If
End If
End Function


快速求解版

Dim selected(10) As Boolean
Private Sub CommandButton1_Click()
h = 1
For i = 123 To 987
For c = 0 To 9
selected(c) = False
Next c
If Not check(i) Then GoTo nnexti
For j = 123 To 987
For c = 0 To 9
selected(c) = False
Next c
If Not check(i) Or Not check(j) Then GoTo nnextj
For k = i+j To 987
For c = 0 To 9
selected(c) = False
Next c
If k = i + j And check(i) And check(j) And check(k) Then
Cells(h, 1) = i
Cells(h, 2) = j
Cells(h, 3) = k
h = h + 1
End If
Next k
nnextj:
Next j
nnexti:
Next i
End Sub

Function check(a)
a1 = Int(a / 100)
a2 = Int((a Mod 100) / 10)
a3 = a - 100 * a1 - 10 * a2
If selected(a1) Then
check = False
Else
selected(a1) = True
If selected(a2) Or a2 = 0 Then
check = False
Else
selected(a2) = True
If selected(a3) Or a3 = 0 Then
check = False
Else
selected(a3) = True
check = True
End If
End If
End If
End Function

本文於 修改第 1 次
回應 回應給此人 推薦文章 列印 加入我的文摘

引用
引用網址:http://city.udn.com/forum/trackback.jsp?no=58536&aid=5469270