0

I am in need of an algorithm that distributes items across multiple arrays. I am coding in PHP if that helps anyone. The criteria is that I want to evenly skip arrays if the number of items is less than the number of arrays. To help you better understand what I am looking for, please review my example problem:

Example:

Consider having 50 lists. I have 20 items I want to distribute to these 50 lists. Some lists will miss out as there are only 20 items. What type of algorithm or what could I do to evenly distribute the items and avoid things like giving the first 20 lists the items and the last 30 lists get nothing?

Edit:

Okay, the objective is that some lists DO NOT receive items. So, only 20 lists would receive items.

Example: There are 8 lists but only 2 items. I want lists 3 and 6 to receive 1 item and then the process would be complete.

Thank you in advance.

3
  • Describe what you think should be "evenly distributed". If you have 50 lists and only 20 items, and each item cannot be divided, the result MUST be 30 empty lists, and 20 lists having 1 item each. Commented Jul 27, 2013 at 22:45
  • Having problems with your homework? This just requires some basic grade-school math to figure out how the items should be distributed, and a simple loop to put the items in the right arrays. What exactly do you not understand? Commented Jul 27, 2013 at 22:46
  • What Sven said. What does it mean that the "first" 20 lists get the items? If you want the result to "look random", put the 20 items in the first 20 lists and then shuffle the lists. Problem solved. Commented Jul 27, 2013 at 22:52

2 Answers 2

1

Put floor(#items/#lists) items in each list.

Then for the remaining items, put one in every floor(#lists/(#items % #lists)).

Sign up to request clarification or add additional context in comments.

Comments

0

Start with some random index in array, and then increment it by length of array + 1 modulo length of array:

function distribute_evenly(lists, items)
  last_index = random(length(lists))

  while length(items) > 0 do
    last_index <- mod(last_index + length(lists) + 1, length(lists))
    push(nth(lists, last_index), pop(items))

There could be other techniques of course, to ensure that the function returns the same result, rather than random one. For example, you could use, as the starting value, either the prime closest to the length of the lists, or the closest power of two or something like that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.