I’m creating a display interface of lets say ‘products’. For this example lets say the display will show at max 4 products. There are a variable number of sources that the products can came from. The number of sources will never be larger than the number of products to display (at most 4 sources for this example). Each source contains 1 or more products. The goal is to evenly distribute the number of products displayed across the sources.
The logic for 4 products would be handled as follows.
- If there is 1 source, then 4 items will be selected from that source.
(4×1) - If there are 4 sources, then 1 item will be selected from each
source. (1×1+1×1+1×1+1×1) - If there are 2 sources, then 2 items will be selected from each
source (2×1+2×1), unless one source only has 1 product, then it will follow as (1×1+3×1) - If there are 3 sources, then 1 item will be selected from 2
sources and 2 items will be selected from 1 source (2×1+1×1+1×1)
Before I start looping to output products, I have a collection of sources and the count of items in each source.
My question is:
What is the simplest way to loop through each source and output the
appropriate amount of products?
Keep in mind that each source may only have 1 product, so it is possible that 4 products cannot be selected.
Here is simple Python code to select the products.
It works by looping over the sources and adding one product at a time.
This should result in a fair distribution between the sources.
The code could be made much more efficient if you find it is too slow.
In this example it prints
to signify taking 1 product from the first source, 2 from the second, and 1 from the third.