Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 187
  • Last Modified:

greatest number of numbers that sums to n

Hi.  I am trying to make a program that takes in a list box (lets call it list1) with a bunch of items in it that have a numerical value.  Next, I have 4 other numbers in a different list.  The point of this is to take a number from the list2 and display all the possibilities in which when you sum up that first card with any number of cards from list1, the total is exactly 11.

Can anyone make me a function that does this? Thank you.
0
cachedVB
Asked:
cachedVB
1 Solution
 
GrahamSkanCommented:
This creates two string arrays.
Indices will show the combination in terms of the list positions of the parts, e.g. "1, 3 ,4"
Values shows the component parts including the number from list2 e.g. "1 + 5 + 5"

Private Sub GetCombinations(List2Number as integer)
Dim Indices() As String
Dim Values() As String
Dim CombinationCount As Integer
Dim Total As Integer
Dim i As Integer
Dim j As Integer
Dim Value As String
Dim Index As String

For i = 1 To (2 ^ List1.ListCount)
    Value = List2Number
    Index = ""
    Total = List2Number
    For j = 0 To List1.ListCount - 1
        If 2 ^ j And i Then
            Total = Total + List1.List(j)
            Index = Index & IIf(Index = "", "", ", ") & j
            Value = Value & " + " & List1.List(j)
        End If
        Next j
    If Total = 11 Then
        ReDim Preserve Indices(CombinationCount)
        ReDim Preserve Values(CombinationCount)
        Indices(CombinationCount) = Index
        Values(CombinationCount) = Value
        CombinationCount = CombinationCount + 1
    End If
Next i
End Sub
0
 
cachedVBAuthor Commented:
Thanks! Just what I wanted... although I had to tweak it a bit to find the longest one. :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now