Excelで複数の数値の中から、特定の合計(例えば100)になる組み合わせの通り数を計算する場合、関数や組み合わせロジックを活用する方法があります。
1. SUM関数と組み合わせ関数を使ったアプローチ
まず、対象の数値をセル範囲に入力します。SUM関数を使って任意の組み合わせの合計を求めることができますが、全ての組み合わせを手動で確認するのは現実的ではありません。
Excelでは直接全組み合わせの計算式はありませんが、VBA(マクロ)を使えば、任意の合計値になる組み合わせを自動で数えることが可能です。
2. VBAで通り数を求める方法
VBAで再帰的に組み合わせをチェックし、SUMが目的の値になる場合にカウントする方法が一般的です。例えば、数値がA1:A10に入力されている場合、VBAで全パターンをチェックし、合計100になる通り数を求めることができます。
3. 具体例
以下のようなVBAコード例で通り数を取得できます。
Function CountCombinations(rng As Range, target As Double) As Long
Dim arr() As Double
Dim i As Long
ReDim arr(1 To rng.Count)
For i = 1 To rng.Count
arr(i) = rng.Cells(i).Value
Next i
CountCombinations = CombinationSum(arr, target, 1, 0)
End Function
Function CombinationSum(arr() As Double, target As Double, pos As Long, currentSum As Double) As Long
Dim count As Long
Dim i As Long
If currentSum = target Then
CombinationSum = 1
Exit Function
End If
If currentSum > target Or pos > UBound(arr) Then
CombinationSum = 0
Exit Function
End If
count = CombinationSum(arr, target, pos + 1, currentSum + arr(pos))
count = count + CombinationSum(arr, target, pos + 1, currentSum)
CombinationSum = count
End Function
4. 注意点
数値の量が多くなると組み合わせの数が指数的に増えるため、処理時間が長くなる場合があります。必要に応じて範囲を絞るなどの工夫が必要です。
5. まとめ
Excelで特定の合計になる組み合わせの通り数を求める場合、VBAを使った再帰処理が現実的です。SUM関数だけでは全組み合わせのチェックは困難なため、VBAで自動化することをおすすめします。


コメント