R
R
ruldo2018-10-01 12:09:48
JavaScript
ruldo, 2018-10-01 12:09:48

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

2 answer(s)
A
Alexey Yarkov, 2018-10-01
@ruldo

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)

#
#, 2018-10-01
@mindtester

your task can be considered as an analogue of cutting a tape of material (3000 units long) into cuts of a given length (1000, 750 and 500)
then it’s already clear where to dig .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question