Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8005053
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T17:06:35+00:00 2026-06-04T17:06:35+00:00

I’m wondering if there’s an algorithm to tell me how many results I’d get

  • 0

I’m wondering if there’s an algorithm to tell me how many results I’d get if I am looking for permutations within bounds.

I have a program that looks for combinations. The best way to explain is it vai an example, say you have 4 items you want to buy at a store: apple,peach,pear and orange. You want to know how much percent you can fit of each into a basket but you tell yourself you want a min. of 20 of each item and a max of 60 of each item(so apple:25, peach:25, pear:25, and orange:25 works perfectly but not apple:0, peach:0, pear:50, and orange:50 because we set a min of 25). If you ran this example, the correct number of items returned would be 1771.

Is there a way to calculate this in advance instead of running the actual program? I have a program that needs to do premuations and I’m trying to find the ideal mix, so I wanted to write a program that gives me the correct output then I’ll do a monte carlo simluation on the inputs to find the mixture of items/ranges I like.

Here’s the program I used(it works in my case when the top band is never used, but if the ranges are tigher, 1-4 then it doesn’t work because it gives me the combinations without considering the ranges):

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(20+4-1,20)  #percent+buckets(items)-1, percent

this gives me the correct answer(1771) because it doesn’t need to factor in the max(60) because its never reached(it only uses 20 as the input). But is there a way I could modify this formula(or use something else) that would tell me how many results to expect if I have something like 40 items with a range of 2-5 or something(something that factors in the max value as well).

Is there an algorithm that can do what I’m looking for?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T17:06:37+00:00Added an answer on June 4, 2026 at 5:06 pm

    You can find the number with the inclusion-exclusion principle. Let distributions(itemCount,bucketCount) be the number of unrestricted distributions of itemCount items to bucketCount buckets. I disregard the lower limit because that’s dealt with simply by subtracting bucketCount*lowerLimit items.

    The number of ways to distribute itemCount items to bucketCount buckets with each bucket containing at most upperLimit items is the number of unrestricted distributions minus the number of unrestricted distributions where at least one bucket contains more than upperLimit items. The latter can be calculated with the inclusion exclusion principle as follows:

    • There are bucketCount choices of a bucket to contain at least upperLimit+1 items, there remain itemCount - (upperLimit+1) items to distribute to bucketCount buckets:

      bucketCount * distributions(itemCount - (upperLimit+1), bucketCount)
      

      must be subtracted from the number of unrestricted distributions.

    • But we have subtracted the distributions where two buckets contain more than upperLimit items twice, we must correct that and add

      nCr(bucketCount,2) * distributions(itemCount - 2*(upperLimit+1), bucketCount)
      

      again, because there are nCr(bucketCount,2) choices of the two buckets.

    • But we have subtracted the distributions where three buckets contain more than upperLimit items thrice, and added it again thrice (nCr(3,2)), so we have to subtract

      nCr(bucketCount,3) * distributions(itemCount - 3*(upperLimit+1), bucketCount)
      

      to rectify that. etc.

    All in all, the number is

     m
     ∑ (-1)^k * nCr(bucketCount,k) * distributions(itemCount - k*(upperLimit+1), bucketCount)
    k=0
    

    where

    m = min { bucketCount, floor(itemCount/(upperLimit+1)) }
    

    (since there is no way to distribute a negative number of items).

    Corrected code from your gist with an implementation of the function to count the ways of distributing the items respecting lower and upper limits:

    import math
    
    def nCr(n,r):
        f = math.factorial
        return f(n) / f(r) / f(n-r)
    
    def itemCount_cal(target, items, minValue):
        return target- items*minValue
    
    def distributions(itemCount, bucketCount):
        # There's one way to distribute 0 items to any number of buckets: all get 0 items
        if itemCount == 0:
            return 1
        # we can't distribute fewer than 0 items, and we need at least one bucket
        if itemCount < 0 or bucketCount < 1:
            return 0
        # If there's only one bucket, there's only one way
        if bucketCount == 1:
            return 1
        #get all possible solutions
        # The number of ways to distribute n items to b buckets is
        # nCr(n+b-1,n)
        f = math.factorial
        return f(itemCount + bucketCount-1)/(f(itemCount) *  f(bucketCount-1))
    
    def ways(items,buckets,lower,upper):
        if upper < lower: # upper limit smaller than lower: impossible
            return 0
        if buckets*upper < items: # too many items: impossible
            return 0
        necessary = buckets*lower
        if items == necessary:  # just enough items to meet the minimum requirement
            return 1
        if items < necessary:   # too few items: impossible
            return 0
        # put the minimum required number in each bucket, leaving
        # items - necessary
        # to distribute
        left = items - necessary
        # We have put 'lower' items in each bucket, so each bucket can now take
        # at most (upper - lower) more
        # any more, and the bucket is overfull
        over = upper + 1 - lower
        # maximal number of buckets we can put more than upper in at all
        # after we fulfilled the minimum requirement
        m = left // over
        # We start with the number of ways to distribute the items disregarding
        # the upper limit
        ws = distributions(left,buckets)
        # Sign for inclusion-exclusion, (-1)**k
        sign = -1
        # Number of overfull buckets
        k = 1
        while k <= m:
            # Add or subtract the number of ways to distribute
            # 'left' items to 'buckets' buckets with
            # k buckets overfull
            #
            # nCr(buckets,k) choices of the buckets we overfill at the start
            #
            # That leaves (left - k*over) items to distribute.
            ws += sign * nCr(buckets,k) * distributions(left - k*over,buckets)
            # flip sign and increment number of overfull buckets
            sign = -sign
            k += 1
        return ws
    

    Note that for large numbers of items and buckets, calculating nCr with the factorial is not the best way, it leads to large intermediate results and uses more operations than necessary.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a small JavaScript validation script that validates inputs based on Regex. I
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.