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

前端 未结 3 801
爱一瞬间的悲伤
爱一瞬间的悲伤 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:09

    Extremely simple solution:

    const splitInteger = (number, parts) => {
        const remainder = number % parts
        const baseValue = (number - remainder) / parts
    
        return Array(parts).fill(baseValue).fill(baseValue + 1, parts - remainder)
    }
    

    To order from largest to smallest:

    const splitInteger = (number, parts) => {
        const remainder = number % parts
        const baseValue = (number - remainder) / parts
    
        return Array(parts).fill(baseValue).fill(baseValue + 1, 0, remainder)
    }
    

    Now as an npm module: split-integer

提交回复
热议问题