我最近遇到了一個問題,我需要弄清楚如何將項目分發到桶中,但我需要找到所有分配方法。桶之間的所有項目分佈
輸入以整數數組的形式出現,它告訴您每列可以容納的最大值,並且數組中必須有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分鐘 – ahitt6345
不,你不是。我個人不同意投票結束這個,這只是一個有點計算機科學的重要問題,而且大多數問題都很簡單,「請幫助解決我的計劃」這種交易,所以這個問題需要更長的時間才能回答。不過,不用擔心,你是在正確的地方,我認爲這是一個深思熟慮的問題。 –
如果我理解你,你想在'maximums'所定義的邊界內找到所有可能的排列,並將它們按'maxItems'或'N'定義的大小進行分組。我對麼? – Xiaoy312