'How to fill a collection with randomly collected elements in limit of total weight?

I have 30 elements with different weight stored as number like 50, 100, 300 etc. After query received with "limit" argument, I need to response with array of randomly collected elements with sum of it weights, not above queried limit with some deviation allowed. As it's elements collected randomly, multiple variations for one query also allowed.

In examples I have deviation set to 30.

  • Example 1, query for limit 560. I response it elements with weights 300, 150, 50, 40 in sum of 540.
  • Example 2, query for limit 160. I response it elements with weights 150, 40 in sum of 190.

I don't know, may be there's some algorithm previously invented for such solutions? Or not and I must develop it by myself?

Thanks much



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source