Discovering the solution to separating an unfamiliar whole number into a specific quantity of nearly equal parts

I could use some assistance with dividing an unknown integer into a specified number of equal or as close to equal parts as possible. The total sum of these parts should equal the original value, and each part must be an integer.

Parameters num: Integer - The number to split into equal parts

parts: Integer - Number of parts to divide the number into

Return Value List (of Integers) - A list of divided parts, ordered from smallest to largest.

This is my current code:


var splitInteger = function(num, parts) {
  // Complete this function
  
  var randombit = num * parts;
  var out = [];
  
  for (var i = 0; i < parts; i++) {
    out.push(Math.random());
  }
  
  var mult = randombit / out.reduce(function(a, b) {
    return a + b;
  });
  
  return out.map(function(el) {
    return el * mult;
  });
}
var d = splitInteger(10, 5)
console.log(d);
console.log("sum - " + d.reduce(function(a, b) {
  return a + b
}));

Sample test cases:

let assert = require("chai").assert;
describe('Challenge', function() {
  it('Simple Functionality', function() {
    assert.deepEqual(splitInteger(10,1), [10]);
    assert.deepEqual(splitInteger(2,2), [1,1]);
    assert.deepEqual(splitInteger(20,5), [4,4,4,4,4]);
  });
});

Expected Output Examples:

num parts Return Value.

Completely even parts example 10 5 [2,2,2,2,2].

Even as can be parts example 20 6 [3,3,3,3,4,4].

An error is occurring in my code.

Answer №1

Here is an alternative approach.

function divideNumber(num, parts) {
  let result;
  let remainder = num % parts;
  if (remainder == 0){
    result = num/parts;
    data = Array(parts).fill(result);
  } else {
    result = (num-remainder)/parts;
    data = Array(parts).fill(result);
    for(i=0;i<remainder;i++){
      data[i] = data[i] + 1;
    }
    data.reverse()
  }

  return data;

}
let dividedNumbers = divideNumber(20, 6)
console.log(dividedNumbers);
console.log("sum - " + dividedNumbers.reduce(function(a,b){return a+b}));

Answer №2

To find the maximum integer coefficient, you can use x/y rounded down to the nearest integer and determine the remainder with x%y. Next, break the remainder into individual 1's and add those 1's to the corresponding number of parts:

const splitIntoSegments = (num, parts) => 
        [...Array(parts)].map((_,i) => 
          0|num/parts+(i < num%parts))

console.log(JSON.stringify(splitIntoSegments(20, 6)));
.as-console-wrapper {min-height: 100%}

Answer №3

An incredibly straightforward solution:

const divideNumber = (number, parts) => {
    const remainder = number % parts
    const baseValue = (number - remainder) / parts

    return Array(parts).fill(baseValue).fill(baseValue + 1, parts - remainder)
}

To arrange from largest to smallest:

const divideNumber = (number, parts) => {
    const remainder = number % parts
    const baseValue = (number - remainder) / parts

    return Array(parts).fill(baseValue).fill(baseValue + 1, 0, remainder)
}

Presented as an npm module: divide-number

Answer №4

I was facing a challenge with this particular problem and none of the previous solutions I found were applicable to the specific cases I needed to address. Fortunately, the following solution proved to be effective for my requirements:

function splitInteger(num, parts) {
    let fractions = Array(parts).fill(num);
    let addedFractionsInst = addedFractions(fractions, parts);
    let integerPartsOfFractionsInst = integerPartsOfFractions(addedFractionsInst, parts);
    let pairWiseDifferenceInst = pairWiseDifference(integerPartsOfFractionsInst, parts);
    return pairWiseDifferenceInst.sort((a, b) => (a-b));
}

function addedFractions(array, parts) {
    let newArray = Array(parts);
    newArray[0] = array[0];
    for (let i = 1; i < array.length; i++) {
        newArray[i] = newArray[i-1] + array[0];
    }
    return newArray;
}

function integerPartsOfFractions(array, parts) {
    let newArray = Array(parts);
    for (let i = 0; i < parts; i++) {
        newArray[i] = Math.trunc(array[i]/parts);
    }
    return newArray;
}

function pairWiseDifference(array, parts) {
    let newArray = Array(parts);
    newArray[0] = array[0];
    for (let i = 1; i < array.length; i++) {
        newArray[i] = array[i] - array[i - 1];
    }
    return newArray;
}

This approach is inspired by the solution provided by user65203 in

Verified to work with the following test cases:

const splitInteger = require('..');
const assert = require('assert')

assert.deepEqual(splitInteger(10,1), [10]);
assert.deepEqual(splitInteger(2, 2), [1,1]);
assert.deepEqual(splitInteger(20,5), [4,4,4,4,4]);
assert.deepEqual(splitInteger(10,4), [2, 2, 3, 3]);
assert.deepEqual(splitInteger(7,4), [1, 2, 2, 2]);
assert.deepEqual(splitInteger(10,8), [1, 1, 1, 1, 1, 1, 2, 2]);
assert.deepEqual(splitInteger(20,6), [3,3,3,3,4,4]);
assert.deepEqual(splitInteger(21,6), [ 3, 3, 3, 4, 4, 4 ]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to establish a connection between MongoDB and Node.js

I recently installed mongoose using npm install mongoose, however, when I attempt to run my JavaScript file it's not connecting. Below is the code snippet: const config = require('config') const express= require('express') const ...

On the second attempt to call setState within the componentDidMount method, it is not functioning as expected

As a newcomer, I am delving into the creation of a memory game. The main objective is to fetch data from an API and filter it to only include items with image links. On level one of the game, the task is to display three random images from the fetched data ...

What is the best way to determine the count of elements in an array that have the active property set to true?

Can anyone help me figure out the most efficient way to solve this problem? (Filter, ng-repeat, or another method?) <div>Number of active items: {{product.length}} </div> //total number of items <div>Number of inactive items: {{product.l ...

Is there a way to trim the current shapes in three.js?

I have created a shape similar to this using Box Geometry at the following link: https://jsfiddle.net/cdu96z3c/. I am looking to achieve a design like the image below by properly utilizing v.x and v.z, while maintaining the current corrugation and properti ...

Can the site be shown in the background?

I have a unique idea for a games website that I want to share. It's a bit difficult to explain, so please bear with me as I try to convey my vision! The inspiration for this project comes from a website called . Have you seen it before? The concept i ...

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

The Google Maps marker is not accurately displaying the designated location

While working on my project, I successfully integrated Google Maps. However, I have encountered a problem: when I search for a specific location, the marker is not displaying at the correct point, but rather somewhere else. The latitude and longitude value ...

Ajax function executing just one time

I'm encountering an issue with my ajax function. I've set it up to run 1912 times, but for some reason, it only runs once. I'm using startAt and stopAt parameters to control the loop, but it's not functioning as expected. Can someone he ...

"Implementing filtering logic for an array of objects with multiple conditions in a React application

I am looking to apply filters to a person list based on criteria such as city, job, age, and gender. How can I apply filters based on five conditions in React? I tried using filter chaining but it did not work for me. In the useEffect hook, I applied indiv ...

Issues encountered with anchor scrolling upon clicking

Hey there, I'm currently working on setting up a contact page that features two forms with a parallax effect. One thing I want to incorporate is an anchor that smoothly scrolls down to the next form when clicked. Despite trying out numerous code snipp ...

Pull in content or data from a separate page by leveraging AJAX

Hello, I'm just starting out in programming and I could really use some help with this issue. index.html <button id="press">Click here</button> <div id="show_image"> </div> <br> <div id="appended_area"></div&g ...

Removing Previously Drawn Elements in Angular Using SVG.js

As a novice full-stack web developer, I recently contributed to the creation of a game-cast app dedicated to ping-pong using the MEAN stack, SVG.js, and sockets. For those interested, here is the GitHub link: https://github.com/ChristopherRoySchneider/ping ...

What is the best way for my JavaScript to identify the index number of the post I wish to remove?

Here is my second question regarding the capstone project I am working on! As part of the project requirements, I need to implement the functionality to delete and edit posts. Currently, my focus is on the delete feature. However, I am unsure about how to ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...

Having trouble with Asp .net ajax autocomplete feature? It seems like the Webmethod is not being triggered as

Could someone explain why the WebMethod is not working on a specific page? The code functions correctly on another page, and even when transferred to a new page. However, when used on the intended page, it fails to trigger the webmethod. I am unsure of wha ...

Issue: "TypeError: Unable to retrieve dynamically imported module" encountered while utilizing dynamic imports in Remix application

I am currently facing an issue with dynamic imports in my Remix application. Whenever I try to dynamically import a module using the code below: const module = await import(../lib/lang/lang-${language.toLowerCase()}.js); An error occurs: TypeError: Fail ...

Mastering the Sequence of JS Functions (or How Promises Still Confuse Me)

Let me explain my objective in simple terms: I have a set of functions that must be executed in a specific order, and each function has its own sub-order. This is how my code looks currently: async function LastModuleFunction() { await FirstModuleFun ...

Buttons and JavaScript: A Comprehensive Compilation

I'm facing an issue with my HTML buttons and JavaScript. When a button is clicked, an AJAX call should be triggered to display data. However, JavaScript seems unable to detect the button. Below is the HTML code: <ul> <li><input ...

I am experiencing difficulties in creating the app while following the Ember.js 2.4 "Introduction" tutorial

Currently delving into the realm of Ember.js, I decided to start by skimming through installation tutorials using npm. Following that, I attempted a brief Getting Started tutorial provided on their website. Without much exploration, I diligently executed e ...