【发布时间】:2017-11-22 00:03:43
【问题描述】:
我最近遇到了一个问题,我需要弄清楚如何将项目分配到存储桶中,但我需要找到所有分配它们的方法。
输入以整数数组的形式出现,告诉您每列可以容纳的最大值,并且数组中必须有 N 个项目。
例如:
maxItems = 3
maximums = [4,2,1] # The order of maximums DOES matter meaning
# This means that the results of maximums = [2,4,1] are different from maximums = [1,2,4]
outputs = [[3,0,0],[2,1,0],[1,1,1],[2,0,1],[0,2,1]] # results are in no particular order
# notice how the sum of each result is equal to maxItems and each value in each of the rows are less than the value inside of maximums
我试图在 javascript 中解决这个问题,但我无法弄清楚如何解决这个问题。我想从用尽可能多的数字填充第一列开始,然后开始向右移动,但是随着最大值数组变大,这种方法变得越来越不准确,我根本不知道如何处理它。
如果您还有其他问题,请随时询问您是否不了解问题。
我开始使用 javascript 的代码是
var all_combinations = function(N, maximums){
var empty = maximums.map(function(){return 0;}); // create empty array size of maximums filled with 0s
var s = 0;
for (var i = 0; i < empty.length && s < N;){
if (empty[i] >= maximums[i]){i++;continue;}
empty[i]++;
s++;
} // fill the left side with as many items as possible
// Then i would proceed to move one item at a time to the right side but some how i would need to do it for the whole array and this is where I get stuck.
};
我尝试搜索此问题,但我从未发现如何按照此处设置的方式进行操作。我试图找到类似的问题,但它们总是与此无关。也许我正在寻找错误的问题。如果有人可以链接一个有用的资源,那就太好了。
如果您有任何问题,请向他们提问。我会尽我所能回答。
【问题讨论】:
-
我是否遗漏了一些信息以使这个问题成为可接受的问题?已经一票接近,甚至不到 5 分钟
-
不,你不是。我个人不同意投票结束这个问题,这只是一个有点计算机科学的问题,而且关于 SO 的大多数问题都是简单的“请帮助修复我的程序”之类的交易,所以这个问题需要更长的时间来回答。不过不用担心,您来对地方了,我认为这是一个经过深思熟虑的问题。
-
如果我理解你的话,你想在
maximums定义的边界内找到所有可能的排列,并按maxItems或N定义的大小对它们进行分组。我说的对吗? -
是的,没错。
-
@Xiaoy312 我相信每个排列中所有值的总和必须等于
maxItems/N
标签: javascript arrays algorithm