How to divide an unknown integer into a given number of even parts using Javascript

前端 未结 3 800
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 21:12

I need help with the ability to divide an unknown integer into a given number of even parts — or at least as even as they can be. The sum of the parts should be the original

3条回答
  •  离开以前
    2021-01-05 22:02

    You may get maximum integer coefficient as x/y rounded down to integer and remainder with x%y. Than simply break remainder into 1's and add those 1's to corresponding number of items:

    const breakIntoParts = (num, parts) => 
            [...Array(parts)].map((_,i) => 
              0|(i < num%parts ? num/parts+1 : num/parts))
    
    console.log(JSON.stringify(breakIntoParts(20, 6)));
    .as-console-wrapper {min-height: 100%}

提交回复
热议问题