Answer the question
In order to leave comments, you need to log in
How to make an algorithm for iterating over all permutation options and the number of numbers so that their sum equals a certain number?
I am writing a cunning calculator for a website and faced the following problem:
There is some height, let's say 3000, you need to compose it from elements 1000, 750 and 500 in all possible ways.
I shoveled a bunch of algorithms, but everywhere only a search of a known number of elements, in my case the number of elements will be different (3 elements: 1000 + 1000 + 1000; 4 elements: 750 + 750 + 1000 + 500, etc.)
How to implement such an algorithm?
Answer the question
In order to leave comments, you need to log in
https://jsfiddle.net/yarkov_aleksei/jwnrbyoc/
const sizes = [1000, 750, 500]
const sum = 3000
function permutation(len, acc = []){
let res = []
sizes.forEach(s => {
let temp = null
if (s === len) {
res.push(acc.concat([s]))
} else if (s < len) {
temp = permutation(len-s, acc.concat([s]))
}
if (temp) {
res = res.concat(temp)
}
})
if (res.length) {
return res
}
}
const result = permutation(sum)
console.log(result)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question