Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have to programmatically distribute a set of items to some entities, but there are rules both on the items and on the entities like so:

Item one: 100 units, only entities from Foo
Item two: 200 units, no restrictions
Item three: 100 units, only entities that have Bar

Entity one: Only items that have Baz
Entity one hundred: No items that have Fubar

I only need to be pointed in the right direction, I'll research and learn the suggested methods.

share|improve this question
What's Foo? What "100 units" means? What's Baz? – MainMa Sep 25 '12 at 21:43
Does it really matter? Its just a set of rules to be matched, it could be "contains gluten" or "is red" – user66160 Sep 25 '12 at 21:48
up vote 1 down vote accepted

The most straightforward way is something like this:

for item in items
    for entity in entities
        if entity.allows(item) and item.allows(entity)

If you have millions of items and entities, and strict performance requirements, then you'd have to get into creating indices for each of the criteria, like a list of all Foo entities, etc. That's going to add a lot of complexity though, so I wouldn't do it unless absolutely necessary.

share|improve this answer
The most straightforward way is also usually the most easily maintained. The next programmer to visit this code will thank you. – Dan Pichelman Sep 25 '12 at 22:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.