今回は、4つの数字の組み合わせ全てで計算してみます。
0から9までの数字を4つ選ぶ方法は10000通りですが、順序の入れ替えを考慮すると715通りです(重複ありの組み合わせです)。715通りで10になるパターンを探すだけなので、計算は意外に重たくないです。
今回は、再帰関数を使いませんでした。(ちなみに、再帰関数を使った場合、途中でループから抜けるのが、少し面倒です。)
計算途中に小数が出てくる(3,4,7,8)(1,1,9,9)(1,3,3,7)のようなパターンは少し難しい感じです。
ソースコードはご自由にご利用ください。ただし、趣味のプログラムなので保証はありません。
'------------------------------
Option Explicit
Dim row As Long
Dim col As Long
Const epsilon As Double = 0.000001
Public Sub Calc10All()
Dim a0 As Long
Dim a1 As Long
Dim a2 As Long
Dim a3 As Long
Sheet1.Cells.Clear
row = 1
col = 1
For a0 = 0 To 9
For a1 = a0 To 9
For a2 = a1 To 9
For a3 = a2 To 9
Sheet1.Cells(row, col + 0) = a0
Sheet1.Cells(row, col + 1) = a1
Sheet1.Cells(row, col + 2) = a2
Sheet1.Cells(row, col + 3) = a3
col = col + 4
Call Calc10All_iterate(a0, a1, a2, a3)
row = row + 1
col = 1
Next a3
Next a2
Next a1
Next a0
End Sub
'演算子の表示
Public Function OperationText(op As Long) As String
OperationText = ""
If op = 0 Then
OperationText = "'+"
ElseIf op = 1 Then
OperationText = "'-"
ElseIf op = 2 Then
OperationText = "'*"
ElseIf op = 3 Then
OperationText = "'/"
End If
End Function
Public Sub Calc10All_iterate(a0 As Long, a1 As Long, a2 As Long, a3 As Long)
'---------- 演算子選択のIndex ----------
Dim i0 As Long
Dim i1 As Long
Dim i2 As Long
'---------- 数字選択のIndex ----------
Dim j0 As Long
Dim j1 As Long
Dim j2 As Long
Dim j3 As Long
Dim j4 As Long
Dim j5 As Long
'------------------------------
Dim a(6) As Double
a(0) = a0
a(1) = a1
a(2) = a2
a(3) = a3
a(4) = 0
a(5) = 0
a(6) = 0
'---------- 1回目の演算 ----------
For i0 = 0 To 3
For j0 = 0 To 3
For j1 = 0 To 3
If j1 = j0 Then
GoTo label0
End If
a(4) = OperationCalc(i0, a(j0), a(j1))
'---------- 2回目の演算 ----------
For i1 = 0 To 3
For j2 = 0 To 4
If j2 = j0 Or j2 = j1 Then
GoTo label1
End If
For j3 = 0 To 4
If j3 = j0 Or j3 = j1 Or j3 = j2 Then
GoTo label2
End If
a(5) = OperationCalc(i1, a(j2), a(j3))
'---------- 3回目の演算 ----------
For i2 = 0 To 3
For j4 = 0 To 5
If j4 = j0 Or j4 = j1 Or j4 = j2 Or j4 = j3 Then
GoTo label3
End If
For j5 = 0 To 5
If j5 = j0 Or j5 = j1 Or j5 = j2 Or j5 = j3 Or j5 = j4 Then
GoTo label4
End If
a(6) = OperationCalc(i2, a(j4), a(j5))
'------------------------------
If Math.Abs(a(6) - 10) < epsilon Then
Sheet1.Cells(row, col + 0) = OperationText(i0)
Sheet1.Cells(row, col + 1) = a(j0)
Sheet1.Cells(row, col + 2) = a(j1)
col = col + 3
Sheet1.Cells(row, col + 0) = OperationText(i1)
Sheet1.Cells(row, col + 1) = a(j2)
Sheet1.Cells(row, col + 2) = a(j3)
col = col + 3
Sheet1.Cells(row, col + 0) = OperationText(i2)
Sheet1.Cells(row, col + 1) = a(j4)
Sheet1.Cells(row, col + 2) = a(j5)
col = col + 3
Sheet1.Cells(row, col) = a(6)
Exit Sub
End If
'------------------------------
label4:
Next j5
label3:
Next j4
Next i2
'------------------------------
label2:
Next j3
label1:
Next j2
Next i1
'------------------------------
label0:
Next j1
Next j0
Next i0
'------------------------------
Sheet1.Cells(row, 14) = "Not 10"
End Sub
0 件のコメント:
コメントを投稿