问题
I have a List
of items containing x items.
I want to distribute these items randomly in other Lists with the conditions :
- Each List has a maximum size of y item (with y = 4)
- Each Item must be used a maximum of z times (with z = 5)
If x isn't divisible by both y and z, it's okay to have Lists containing less than y items.
I'm looking for a Java (from 1.6 to 1.8) implementation of such a method. Thanks!
EDIT
Here's what I tried so far :
List<Item> myItems; // Initialized in an other part
int y, z; // Initialized in an other part
int x = myItems.size();
List<List<Item>> myList = new ArrayList<List<Item>>();
int a = (int) Math.ceil((double)x/y);
Random random = new Random(new Random().nextInt());
for (int j = 0; j < a; j++) {
myList.add(j, new ArrayList<Item>());
}
for (int i = 0; i < x; i++) {
int r = random.nextInt(a);
while (myList.get(r).size() >= y) {
r = random.nextInt(a);
}
myList.get(r).add(myItems.get(i));
}
// Here myList is populated
回答1:
The following code should work. I've assumed here that the total number of items in the list shouldn't change.
public List<List<Item>> distribute(List<Item> list, int y, int z) {
int x = list.size();
int nLists = (int) Math.ceil((double)x/y);
// Create result lists
List<List<Item>> result = new ArrayList<>();
for (int j = 0; j < nLists; j++)
result.add(new ArrayList<Item>());
List<List<Item>> outputLists = new ArrayList<>(result);
// Create item count store
Map<Item, Integer> itemCounts = new HashMap<>();
for (Item item : list)
itemCounts.put(item, 0);
// Populate results
Random random = new Random();
for (int i = 0; i < x; i++) {
// Add a random item (from the remaining eligible items)
// to a random list (from the remaining eligible lists)
Item item = list.get(random.nextInt(list.size()));
List<Item> outputList = outputLists.get(random.nextInt(outputLists.size()));
outputList.add(item);
// Manage eligible output lists
if (outputList.size() >= y)
outputLists.remove(outputList);
// Manage eligible items
int itemCount = itemCounts.get(item).intValue() + 1;
if (itemCount >= z)
list.remove(item);
else
itemCounts.put(item, itemCount);
}
return result;
}
Note: the above code mutates the original list. If that is not desired, you should create a copy of the list at the start.
With the following input:
list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
y = 4
z = 3
This gives output lists such as:
[1,10,17,2]
[2,24,6,26]
[16,23,21]
[8,0,3,13]
[12,11,6,0]
[2,17,14,7]
[0,27,7,12]
[7,19,3]
During that run, items 0
, 2
, and 7
reached the z
limit, and were not used again.
来源:https://stackoverflow.com/questions/28502970/random-distribution-of-items-in-list-up-to-a-maximum-count