Answer the question
In order to leave comments, you need to log in
How to scatter elements as randomly as possible according to the condition?
Hello. There are x stacks, each can contain a different number of blocks y (each stack has its own y). You are given z blocks ( z is less than or equal to the sum of the blocks in the stack (y1 + y2 + y3 ... yn)). It is necessary to randomly place these blocks (z) in piles so that there are no extra blocks left. It doesn't have to be done in one pass, but the fewer the better. It is also allowed that in one of the stacks after the placement there will be no blocks.
Answer the question
In order to leave comments, you need to log in
in JS, easy to convert to C#
function randomSets(boxSizes, z) {
const arr = [];
const result = [];
for (let i = 0; i < boxSizes.length; ++i) {
result.push([]);
const y = boxSizes[i];
for (let j = 0; j < y; ++j) {
arr.push(i);
}
}
let len = arr.length;
for (let i = 0; i < z && len > 0; ++i) {
const pos = Math.floor(Math.random() * len);
result[arr[pos]].push(i);
arr[pos] = arr[--len];
}
return result;
}
const fill = randomSets([1, 2, 2], 5); // в качестве блоков - номера от 0 до z-1
[
[1], // содержимое 0 стопки
[0, 4], // содержимое 1 стопки
[2, 3] // содержимое 2 стопки
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question