View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.misc
Maistrye Maistrye is offline
external usenet poster
 
Posts: 1
Default Finding pieces of a value in a table


Here's some code that will give you an answer for this.

It assumes your values are in A1:A22 and that you want the answers in
B1:B22. (in Sheet1)

Scott

---------
Option Explicit

Const N = 22
Const SolveVal = 252

Dim X(N - 1) As Long
Dim Answer(N - 1) As Long

Function FindAnswer(Val As Long, Sum As Long) As Boolean
If (Sum = SolveVal) Then
FindAnswer = True
Exit Function
ElseIf (Val = N Or Sum SolveVal) Then
FindAnswer = False
Exit Function
End If

Answer(Val) = 1
If (FindAnswer(Val + 1, Sum + X(Val)) = True) Then
FindAnswer = True
Exit Function
End If

Answer(Val) = 0
If (FindAnswer(Val + 1, Sum) = True) Then
FindAnswer = True
Exit Function
End If

FindAnswer = False
End Function

Sub SubsetSum()
Dim W As Worksheet
Dim i As Long

Set W = Worksheets("Sheet1")

For i = 1 To N
X(i - 1) = W.Cells(i, 1)
Next i

If (FindAnswer(0, 0) = True) Then
For i = 1 To N
W.Cells(i, 2) = Answer(i - 1)
Next i
Else
MsgBox ("No solution")
End If
End Sub


--
Maistrye
------------------------------------------------------------------------
Maistrye's Profile: http://www.excelforum.com/member.php...o&userid=36078
View this thread: http://www.excelforum.com/showthread...hreadid=563728