Enumeration of combinations of N balls in A boxes?

后端 未结 8 1072
后悔当初
后悔当初 2020-12-30 18:06

I want to enumerate all possible combinations of N balls in A boxes.

example: I have 8

8条回答
  •  长情又很酷
    2020-12-30 19:03

    Pseudocode:

    Enumerate(Balls, Boxes)
      if Boxes<=0 
        Error
      elseif Boxes=1 
        Box[1] = Balls
        PrintBoxes
      else
        forall b in 0..Balls 
          Box[Boxes] = b
          Enumerate(Balls-b, Boxes-1)
        endfor
      endif
    end
    

    Explanation

    Start at the first box, if there are no boxes, complain and quit. If it is the last box to be filled, drop all remaining balls and show the result. If there are more boxes, first add 0 balls and repeat the procedure with the other boxes. Then add 1, ball 2 balls until there are no balls left.

    To show, that the algorithm works, I give an example with real values, 3 balls and 2 boxes.

    We have an array of boxes called Box, and each box can hold any number of balls (the value). PrintBoxes prints the current value of the boxes.

    Box = (0,0)
    Enumerate(3, 2)
      b=0
      Box = (0,0)
      Enumerate(3,1)
        Box = (3,0) 
        Print!
      b=1 
      Box = (0,1)
      Enumerate(2,1)
        Box = (2,1)
        Print!
      b=2
      Box = (0,2)
      Enumerate(1,1)
        Box = (1,2)
        Print!
      b=3   
      Box = (0,3)
      Enumerate(0,1)
        Box = (0,3)
        Print!
    
     Output:
    
     (3,0)
     (2,1)
     (1,2)
     (0,3)
    
     Which are all the combinations.
    

    Another example with 3 boxes and 3 balls:

    Box = (0,0,0)
    Enumerate(3, 3)
      b=0
      Box = (0,0,0)
      Enumerate(3,2)
        b=0
        Box = (0,0,0)
        Enumerate(3,1)
          Box = (3,0,0)
        b=1
        Box = (0,1,0)
        Enumerate(2,1)
          Box = (2,1,0)
        b=2
        Box = (0,2,0)
        Enumerate(1,1)
          Box = (1,2,0)
        b=3
        Box = (0,3,0)
        Enumerate(0,1)
          Box = (0,3,0)
      b=1 
      Box = (0,0,1)
      Enumerate(2,2)
        b=0
        Box = (0,0,1)
        Enumerate(2,1)
          Box = (2,0,1)
        b=1
        Box = (0,1,1)
        Enumerate(1,1)
          Box = (1,1,1)
        b=2
        Box = (0,2,1)
        Enumerate(0,1)
          Box = (0,2,1)
      b=2
      Box = (0,0,2)
      Enumerate(1,2)
        b=0
        Box = (0,0,2)
        Enumerate(1,1)
          Box = (1,0,2)
        b=1
        Box = (0,1,2)
        Enumerate(0,1)
          Box = (0,1,2)
      b=3   
      Box = (0,0,3)
      Enumerate(0,2)
        b=0
        Box = (0,0,3)
        Enumerate(0,1)
          Box = (0,0,3)
    
    Output
    (3,0,0)
    (2,1,0)
    (1,2,0)
    (0,3,0)
    (2,0,1)
    (1,1,1)
    (0,2,1)
    (1,0,2)
    (0,1,2)
    (0,0,3)
    

提交回复
热议问题