[Solved] EXCEL VBA FOR POSSIBLE COMBINATIONS DEPENDING ON CELLS VALUES


With your latest explanation and comparing your example results with mine, I believe I now understand your requirement.

You have the parameters placed on a worksheet and output the results to the same worksheet. I do not want to tie the generation code to a particular style of input or output and have coded a subroutine:

Sub Generate(ByVal MinAdultsPerRoom As Long, ByVal MaxAdultsPerRoom As Long, _
             ByVal MinChildrenPerRoom As Long, ByVal MaxChildrenPerRoom As Long, _
             ByVal MaxPersonsPerRoom As Long, ByRef ChildAgeRanges() As String, _
             ByVal MaxChildrenPerRange As Long, ByRef Results() As String)

In my test routine, I have called this routine so:

  Call Generate(1, 3, 1, 3, 4, ChildAgeRanges, 3, Results)

and

  Call Generate(0, 2, 0, 4, 5, ChildAgeRanges, 4, Results)

The first call matches your example. The second tests and demonstrates other capabilities on the routine. For the first call, the parameters map to your worksheet:

MinAdultsPerRoom       Load from B2
MaxAdultsPerRoom       Load from C2
MinChildrenPerRoom     See below
MaxChildrenPerRoom     See below
MaxPersonsPerRoom      Load from D2
ChildAgeRanges()       Load from row 7
MaxChildrenPerRange    See below
Results()              Write to columns B and C starting from row 10

You have no equivalent to the parameters labelled “See below.” It seemed to me that these parameters were required for your output. For example, in your example, you have a minimum of 1 child per room and I could not see where this value was specified. I am not sure now that these parameters are necessary but I have decided not to remove them in case they are useful. The second call demonstrates the use of these parameters.

The array Results contains the combinations ready for output to a worksheet in the style used in your example.

My test routine uses the following calls to output the parameters and the results:

  Call OutParametersAndResults("Sheet2", ColOut, 1, 3, 1, 3, 4, ChildAgeRanges, 3, Results)   

and

  Call OutParametersAndResults("Sheet2", ColOut, 0, 2, 0, 4, 5, ChildAgeRanges, 4, Results)

My output is similar to yours but not identical since my output is structured for convenient testing. By replacing macros Test and OutParametersAndResults with your own code, you can load parameters and output results as you wish. The macro Generate should not require changes.


This section is a brief description of how macro Generate works. However, I suspect you will find it easier to copy my code to a new workbook, run Test and study the output.

I have two arrays. The first, Working is two dimensional and is used to store accepted combinations during the generation process. The second, WorkingCrnt is one dimensional and is used to generate possible combinations.

The arrangement of WorkingCrnt is:

Number          Number of range    Number of range    ...
of adults       1 children         2 children         ...

Row 20 of your data: 1ADT+3CHD (0-02,99)(0-02,99)(03-06,99) would be represented in WorkingCrnt as:

   1                  2                  1              0

That is, as 1 adult + 2 range-1 children + 1 range-2 children + 0 range-3 children.

The value ranges for the elements of WorkingCrnt are:

Min adults      Min children       Min children
   To            to                 to
Max adults      Max children       Max children

The secret is to systematically generate possible combinations, to reject individual combinations that fail validation checks and to stop generating combinations when it is impossible for any future combination to be valid. For example, after:

   1                  2                  1              0

the next possible combination is:

   1                  2                  2              0

This combination will be rejected because it has five people which exceeds the maximum for the room. This means there is no point testing any of:

   1                  2                  3              0
   1                  2                  1              1
   1                  2                  1              2
   1                  2                  1              3

Not generating these combinations and not testing them can substantially reduce the duration of the generation process.


I hope the code below contains enough comments to explain what it does and how. Diagnostics are output to the Immediate Window to help both test and understand the routine.

Option Explicit
Sub Test()

  Dim ColOut As Long
  Dim ChildAgeRanges() As String
  Dim Results() As String

  ColOut = 1

  ReDim ChildAgeRanges(1 To 3)
  ChildAgeRanges(1) = "(0-02,99)"
  ChildAgeRanges(2) = "(03-06,99)"
  ChildAgeRanges(3) = "(07-12,99)"

  Call Generate(1, 3, 1, 3, 4, ChildAgeRanges, 3, Results)

  Call OutParametersAndResults("Sheet2", ColOut, 1, 3, 1, 3, 4, ChildAgeRanges, 3, Results)

  ReDim ChildAgeRanges(1 To 4)
  ChildAgeRanges(1) = "(0-2)"
  ChildAgeRanges(2) = "(3-6)"
  ChildAgeRanges(3) = "(7-12)"
  ChildAgeRanges(4) = "(13-15)"

  Call Generate(0, 2, 0, 4, 5, ChildAgeRanges, 4, Results)

  Call OutParametersAndResults("Sheet2", ColOut, 0, 2, 0, 4, 5, ChildAgeRanges, 4, Results)

End Sub
Sub Generate(ByVal MinAdultsPerRoom As Long, ByVal MaxAdultsPerRoom As Long, _
             ByVal MinChildrenPerRoom As Long, ByVal MaxChildrenPerRoom As Long, _
             ByVal MaxPersonsPerRoom As Long, ByRef ChildAgeRanges() As String, _
             ByVal MaxChildrenPerRange As Long, ByRef Results() As String)

  ' On return Result contains one row per combination of people that
  ' can occupy a hotel room.

  ' MinAdultsPerRoom     The minimum number of adults in a room
  ' MaxAdultsPerRoom     The maximum number of adults in a room. If all
  '                      occupants of a room can be adults, the calling
  '                      routine should set this to MaxPersonsPerRoom.
  ' MinChildrenPerRoom   The minimum number of children in a room
  ' MaxChildrenPerRoom   The maximum number of children in a room. If all
  '                      occupants of a room can be children, the calling
  '                      routine should set this to MaxPersonsPerRoom.
  ' MaxPersonsPerRoom    The maximum number of persons (adults or children)
  '                      in a room.
  ' ChildAgeRanges       A string array listing all the age ranges for
  '                      children. These should be of the form "(n-m)" but the
  '                      routine does not check this.
  ' MaxChildrenPerRange  The maximum number of children that can be within the
  '                      same age range. If there is no maximum, the calling
  '                      routine should set this to MaxChildrenPerRoom.
  ' Result               The string array in which the possible combinations
  '                      are returned.  On return, it will have two columns
  '                      and one row per combination.  The columns will
  '                      contain:
  '                         1  A string of the form nADT+mCHD where n is the
  '                            number of adults and m the number of children.
  '                         2  A string of the form "(n-m)" or "(n-m)(p-q)"
  '                            or similar. The substrings "(n-m)", "(p-q)" and
  '                            so on are taken unchecked from ChildAgeRanges.

  ' Check for parameter values that will break code
  ' Execution will stop with one of these statements highlighted if a
  ' parameter value or combination of parameter values is forbidden.
  Debug.Assert MaxAdultsPerRoom + MaxChildrenPerRoom > 0
  Debug.Assert MinAdultsPerRoom <= MaxAdultsPerRoom
  Debug.Assert MinChildrenPerRoom <= MaxChildrenPerRoom
  Debug.Assert MaxPersonsPerRoom >= MinAdultsPerRoom + MinChildrenPerRoom
  Debug.Assert MaxAdultsPerRoom <= MaxPersonsPerRoom
  Debug.Assert MaxChildrenPerRoom <= MaxPersonsPerRoom

  Dim ColWorkCrnt As Long
  Dim ColWorkMax As Long
  Dim FirstCombinationForNewNumOfAdults As Boolean
  Dim InvalidCombination As Boolean
  Dim InxAdultCrnt As Long
  Dim InxChildCrnt As Long
  Dim InxRangeCrnt As Long
  Dim NumChildrenInRange As Long
  Dim NumChildrenInRoom As Long
  Dim NumRanges As Long
  Dim RowWorkCrnt As Long
  Dim RowWorkMax As Long
  Dim StepBack As Boolean
  Dim Working() As Long
  Dim WorkingSingle() As Long

  NumRanges = UBound(ChildAgeRanges) - LBound(ChildAgeRanges) + 1

  ' Working is the array in which the details of possible combinations are
  ' accumulated in a format convenient for processing.
  ' The columns are:
  '   1  Number of adults for this combination
  '   2  Number of children within first age range
  '   3  Number of children within second age range
  '   :     :         :        :           :
  ' It is theoretically possible to calculate the number of combinations for
  ' a given set of parameters.  However, this would be a difficult calculation
  ' and the benefits are not obvious.  With a maximum of 6 per room and 5
  ' different age ranges and no restriction of age mix, there are only 46,656
  ' combination for which the memory requirements are less than 750,000 bytes.
  ' So the array is dimensioned to hold the maximum number of combinations

  ColWorkMax = 1 + NumRanges
  ReDim Working(1 To ColWorkMax, 1 To MaxPersonsPerRoom ^ (1 + NumRanges))
  RowWorkMax = 0        ' The last used row

  ReDim WorkingSingle(1 To ColWorkMax)     ' Used to build one row of Working

  ' Initialise WorkingSingle with:
  '   Element 1 = Minimum number of adults per room
  '   Element Max = 1
  '   Other elements = 0
  WorkingSingle(1) = MinAdultsPerRoom
  WorkingSingle(ColWorkMax) = MinChildrenPerRoom
  If MinAdultsPerRoom + MinChildrenPerRoom = 0 Then
    ' Both adults and children are optional but must have
    ' at least one person in the initial combination.
    If MaxChildrenPerRoom > 0 Then
      ' Can have a child in room
      WorkingSingle(ColWorkMax) = 1
    Else
      WorkingSingle(1) = 1
    End If
  End If
  FirstCombinationForNewNumOfAdults = True

  For ColWorkCrnt = 2 To ColWorkMax - 1
    WorkingSingle(ColWorkCrnt) = 0
  Next

  ' Output headers for diagnostics
  For InxRangeCrnt = LBound(ChildAgeRanges) To UBound(ChildAgeRanges)
    Debug.Print " R" & InxRangeCrnt & " = " & ChildAgeRanges(InxRangeCrnt)
  Next
  Debug.Print Space(9) & " A";
  For InxRangeCrnt = LBound(ChildAgeRanges) To UBound(ChildAgeRanges)
    Debug.Print " R" & InxRangeCrnt;
  Next
  Debug.Print

  Do While True

    ' Is WorkingSingle a valid combination?
    InvalidCombination = False
    NumChildrenInRoom = 0
    For ColWorkCrnt = 2 To ColWorkMax
      NumChildrenInRoom = NumChildrenInRoom + WorkingSingle(ColWorkCrnt)
    Next
    If NumChildrenInRoom > MaxChildrenPerRoom Then
      InvalidCombination = True
    ElseIf NumChildrenInRoom + WorkingSingle(1) > MaxPersonsPerRoom Then
      InvalidCombination = True
    End If

    If Not InvalidCombination Then
      ' Save accepted combination
      RowWorkMax = RowWorkMax + 1
      For ColWorkCrnt = 1 To ColWorkMax
        Working(ColWorkCrnt, RowWorkMax) = WorkingSingle(ColWorkCrnt)
      Next
      ' Output accepted combination
      Debug.Print "Accepted ";
      For ColWorkCrnt = 1 To ColWorkMax
      Debug.Print Right(" " & WorkingSingle(ColWorkCrnt), 2) & " ";
      Next
      Debug.Print
    Else
      ' Output rejected combination
      Debug.Print "Rejected ";
      For ColWorkCrnt = 1 To ColWorkMax
        Debug.Print Right(" " & WorkingSingle(ColWorkCrnt), 2) & " ";
      Next
      Debug.Print
    End If

    ' Find last non-zero column in WorkingSingle
    For ColWorkCrnt = ColWorkMax To 1 Step -1
      If WorkingSingle(ColWorkCrnt) > 0 Then
        Exit For
      End If
    Next

    If NumChildrenInRoom + WorkingSingle(1) >= MaxPersonsPerRoom Then
      ' Either this combination or the next would exceed the room limit
      If ColWorkCrnt = 1 Then
        ' All combinations have been generated
        Exit Do
      Else
        ' Can do nothing more with this column. Try previous
        WorkingSingle(ColWorkCrnt) = 0
        ColWorkCrnt = ColWorkCrnt - 1
        StepBack = True
      End If
    Else
      ' Continue with current and following columns
      StepBack = False
    End If

    Do While True
      ' Loop until new combination generated or no new combination is possible
      ' FirstCombinationForNewNumOfAdults ensure that if zero children are
      ' permitted, so first non-zero column is 1, the number of adults is
      ' not immediately stepped.
      If ColWorkCrnt = 1 And Not FirstCombinationForNewNumOfAdults Then
        ' Adult column
        WorkingSingle(ColWorkCrnt) = WorkingSingle(ColWorkCrnt) + 1
        WorkingSingle(ColWorkMax) = MinChildrenPerRoom
        FirstCombinationForNewNumOfAdults = True
        'Check for all combinations having been generated outside this loop
        Exit Do
      Else
        ' Child column
        FirstCombinationForNewNumOfAdults = False
        If WorkingSingle(ColWorkCrnt) >= MaxChildrenPerRange Then
          ' This column cannot be increased
          If StepBack Or ColWorkCrnt = ColWorkMax Then
            ' All combinations of following columns have been
            ' considered or there are no following columns.
            ' Can do nothing more with this column. Try previous
            WorkingSingle(ColWorkCrnt) = 0
            ColWorkCrnt = ColWorkCrnt - 1
            StepBack = True
          Else
            ' Not all possible combinations of following columns
            ' have been considered.  Start with last
            WorkingSingle(ColWorkMax) = 1
            Exit Do
          End If
        Else
          ' This column can be increased
          If StepBack Or ColWorkCrnt = ColWorkMax Then
            ' All possible values for following columns have been
            ' considered or there are no following columns
            ' Step this column which is not at maximum
            WorkingSingle(ColWorkCrnt) = WorkingSingle(ColWorkCrnt) + 1
          Else
            ' Not all possible combinations of following columns
            ' have been considered
            WorkingSingle(ColWorkMax) = 1
            Exit Do
          End If
          Exit Do
        End If
      End If

    Loop  ' until next combination generated

    If WorkingSingle(1) > MaxAdultsPerRoom Then
      ' All combinations have been generated
      Exit Do
    End If

  Loop  ' until all combinations generated

  ' Working contains all acceptable combination
  ' Generate Results from Working

  ' Note this is sized ready to be written to a worksheet
  ' with the rows as the first dimension.
  ReDim Results(1 To RowWorkMax, 1 To 2)

  For RowWorkCrnt = 1 To RowWorkMax

    ' Calculate number of children and number of different age ranges
    NumChildrenInRoom = 0

    For ColWorkCrnt = 2 To ColWorkMax
      If Working(ColWorkCrnt, RowWorkCrnt) <> 0 Then
        NumChildrenInRoom = NumChildrenInRoom + Working(ColWorkCrnt, RowWorkCrnt)
      End If
    Next

    ' Note row number in Working and Results are the same
    Results(RowWorkCrnt, 1) = Working(1, RowWorkCrnt) & "ADT"
      Results(RowWorkCrnt, 2) = ""
    If NumChildrenInRoom > 0 Then
      Results(RowWorkCrnt, 1) = Results(RowWorkCrnt, 1) & "+" & NumChildrenInRoom & "CHD"
      For ColWorkCrnt = 2 To ColWorkMax
        NumChildrenInRange = Working(ColWorkCrnt, RowWorkCrnt)
        If NumChildrenInRange > 0 Then
          If NumChildrenInRange = NumChildrenInRoom Then
            ' All children in combination have same age range
            Results(RowWorkCrnt, 2) = ChildAgeRanges(ColWorkCrnt - 2 + LBound(ChildAgeRanges))
          Else
            ' Children are of different age ranges
            Do While NumChildrenInRange > 0
              Results(RowWorkCrnt, 2) = Results(RowWorkCrnt, 2) & _
                                        ChildAgeRanges(ColWorkCrnt - 2 + LBound(ChildAgeRanges))
              NumChildrenInRange = NumChildrenInRange - 1
            Loop
          End If
        End If
      Next
    End If
  Next

End Sub
Sub OutParametersAndResults(ByVal WshtName As String, ByRef ColOut As Long, _
                           ByVal MinAdultsPerRoom As Long, ByVal MaxAdultsPerRoom As Long, _
                           ByVal MinChildrenPerRoom As Long, ByVal MaxChildrenPerRoom As Long, _
                           ByVal MaxPersonsPerRoom As Long, ByRef ChildAgeRanges() As String, _
                           ByVal MaxChildrenPerRange As Long, ByRef Results() As String)

  ' Output the parameters and results for a call of Generate.

  ' WshtName          The name of the worksheet to which the parameters and results
  '                   are to be output.
  ' ColOut            The rows used by the routine are fixed with output of
  '                   parameters starting on row 3.  The value of ColOut determines
  '                   the first of the three columns used. At the end of routine
  '                   ColOut is stepped by 4 so if the routine is called again,
  '                   output will be further to the right.
  ' Other parameters  Copies of the parameters for and results from macro Generate.

  Dim InxRangeCrnt As Long
  Dim Rng As Range
  Dim RowCrnt As Long

  With Worksheets(WshtName)

    .Cells(3, ColOut + 1).Value = "Minimum"
    .Cells(3, ColOut + 2).Value = "Maximum"
    .Cells(4, ColOut).Value = "Adults per room"
    .Cells(4, ColOut + 1).Value = MinAdultsPerRoom
    .Cells(4, ColOut + 2).Value = MaxAdultsPerRoom
    .Cells(5, ColOut).Value = "Children per room"
    .Cells(5, ColOut + 1).Value = MinChildrenPerRoom
    .Cells(5, ColOut + 2).Value = MaxChildrenPerRoom
    .Cells(6, ColOut).Value = "Persons per room"
    .Cells(6, ColOut + 2).Value = MaxPersonsPerRoom
    .Cells(7, ColOut).Value = "Children per range"
    .Cells(7, ColOut + 2).Value = MaxChildrenPerRange
    .Cells(8, ColOut).Value = "Age ranges"
    RowCrnt = 8
    For InxRangeCrnt = LBound(ChildAgeRanges) To UBound(ChildAgeRanges)
      .Cells(RowCrnt, ColOut + 1).Value = ChildAgeRanges(InxRangeCrnt)
      RowCrnt = RowCrnt + 1
    Next

    RowCrnt = RowCrnt + 1

    Set Rng = Range(.Cells(RowCrnt, ColOut), .Cells(RowCrnt + UBound(Results) - 1, ColOut + 1))
    Rng.Value = Results
    Rng.Sort Key1:=.Cells(RowCrnt, ColOut), Order1:=xlAscending, _
             Key2:=.Cells(RowCrnt, ColOut + 1), Order2:=xlAscending, _
             Header:=xlNo

    Rng.EntireColumn.AutoFit

 End With

 ' Prepare for possible further output
 ColOut = ColOut + 4

End Sub

solved EXCEL VBA FOR POSSIBLE COMBINATIONS DEPENDING ON CELLS VALUES