View Single Post
  #7   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


root Wrote:
Scott,
Thanx for the code. It works. Would this give me the first solution it
finds? What if there are multiple solutions?


It gives the first solution it finds.

It can be modified to give the Nth solution it finds fairly easily.

Try this code. You can probably modify it to make it more robust, but
it should do the trick.

Scott

--------

Option Explicit

Const N = 22
Const SolveVal = 252

Dim SolNumber As Long
Dim SolTarget As Long
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
SolNumber = SolNumber + 1
If (SolNumber = SolTarget) Then
FindAnswer = True
Else
FindAnswer = False
End If
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

SolNumber = 0
SolTarget = InputBox("Enter solution number:")

If (FindAnswer(0, 0) = True) Then
For i = 1 To N
W.Cells(i, 2) = Answer(i - 1)
Next i
Else
If (SolTarget SolNumber) Then
MsgBox ("Only " & SolNumber & " solutions.")
Else
MsgBox ("No solution.")
End If
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