Discovering the fewest amount of paper currency and their corresponding values needed to reach a specified sum in an array

When attempting to retrieve the value 2316, the result is [0,2,0,3,0,0,2,1,0,1] instead of the expected output [0,2,0,3,0,0,1,1,0,1]. It seems like there may be an issue with the algorithm I am using.

function findNoteAndCoins(salary) {
  var note = [5000,1000,500,100,50,20,10,5,2,1];
  var noteCount = new Array(10);
  noteCount = Array.from(noteCount, item => item || 0);

    for(var i = 0; i < 10; i++){
        if (salary >= note[i]){
            noteCount[i]= salary / note[i];
            salary = salary % note[i];
        }
    }

   for(var j = 0; j < 10; j++){
        if (noteCount[j] != 0){
            var count = noteCount[j];
        }
    }

  return noteCount.map(num => (num * 1).toFixed(0));  
}

findNoteAndCoins(2316);

Answer №1

To change a floating-point number of notes to an integer, utilize either Math.trunc or Math.floor: Math.trunc(remaining / note)

The function could be implemented like this:

function calculateNotesAndCoins(amount) {
  const denominations = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];
  const countOfDenominations = [];

  let remains = amount;
  for (const denom of denominations) {
    if (amount >= denom) {
      countOfDenominations.push(Math.trunc(remains / denom));
      remains = remains % denom;
    } else {
      countOfDenominations.push(0);
    }
  }

  return countOfDenominations;
}

console.log(calculateNotesAndCoins(2316));

You can verify the accuracy of the calculateNotesAndCoins method as follows:

function determineAmount(denomCounts) {
  const denominations = [5000, 1000, 500, 100, 50, 20, 10, 5, 2, 1];
  let amount = 0;
  for (let i = 0; i < denomCounts.length; i++) {
    amount += denomCounts[i] * denominations[i];
  }
  return amount;
}

console.log(determineAmount(calculateNotesAndCoins(2316)) === 2316);

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

Error encountered while trying to access the user information from Firestore/Firebase

When I attempt to display the current user that is logged in console.log(firebase.auth().currentUser.uid) The user's UID is outputted. I then decided to retrieve the current user's information from Firestore using the following code: import ...

What is the best way to determine if a value from my array is present within a different object?

I have an array with oid and name data that I need to compare against an object to see if the oid value exists within it. Here is the array: const values = [ { "oid": "nbfwm6zz3d3s00", "name": "" ...

What is the process for reaching individuals within a nested object?

I have been struggling to access the elements of a nested object without any success. Despite looking through similar questions on stackexchange (such as this), I have not been able to resolve my issue. I attempted to access the final element using console ...

Nodejs client application for maintaining constant communication with an echo server

As someone who is just starting out in the world of nodejs, I recently managed to create an echo server using tutorials from YouTube. While there's nothing wrong with my server code, I am now facing the challenge of developing a client program that ca ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

Classic ASP offers a feature that allows users to select all checkboxes at once

I'm looking to create a functionality where there is a 'Select all' checkbox along with individual checkboxes for each database record. Is it possible to use JavaScript to ensure that when the 'Select all' checkbox is checked, all ...

Crisp edges and corners casting shadows in Threejs BoxGeometry

I created a structure using BoxGeometry, with a DirectionalLight rotating around it. However, I am facing an issue with aliased light bleed in the corners. I've attempted adjusting the shadow.mapSize, the blur radius, and the renderer.shadowMap.type, ...

Webpack is having trouble resolving modules from the subdirectory of a package

I am facing an issue with a package I am working on, which is structured as follows: - lib/ -- moduleA/ ---- index.js -- moduleB/ ---- index.js - src/ -- moduleA/ -- moduleB/ The package.json file specifies: "main": "./lib" When trying to import a spec ...

What could be causing my Next.js application to not function properly on Safari?

With my current project of developing a web app using nextjs, I'm encountering an issue specifically on Safari browser for Mac. Surprisingly, everything works perfectly fine on other browsers and even on iPhone. Upon opening the developer console, thi ...

What is the method for calculating the number of elements in arrays using C programming?

#include <stdio.h> #include <string.h> int main() { char name[32][32]; char input[32]; int number; int i; for(i=0;i<10;i++) { fgets(input,sizeof(input),stdin); sscanf(input,%s,name[i]); } //Assume we have an unknown number of el ...

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

The notion of await goes beyond simply waiting for a promise to be fulfilled

Hey there everyone! I've been struggling with a problem for some time now, and I just can't seem to figure it out by simply searching online. That's why I'm turning to all of you for help. Situation: I'm working on a small applic ...

nodemon is launching an endless number of .node-xmlhttprequest-sync files

I am facing a strange issue with my app that imports a module containing a promise. Everything runs smoothly when I start the app using "node app.js" However, if I use "nodemon" to launch it, it constantly creates files with names like .node-xmlhttpreque ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

Error: Jasmine unit test failed due to a connection refusal

While running the unit test in jasmine using the ng test command, an error occurred. Previously, everything was configured correctly and working well. I'm not sure why this error suddenly appeared. Error message in browser: Description: Connection ...

"Error: The chai testing method appears to be improperly defined and is not

I am trying to set up a Mocha and Chai test. Here is my class, myClass.js: export default class Myclass { constructor() {} sayhello() { return 'hello'; }; } Along with a test file, test.myclass.js: I am attempting to a ...

Experiencing issues with properly rendering the Bootstrap year calendar and encountering difficulties with the date picker functionality

Having trouble implementing the bootstrap-year-calendar on my website. The JavaScript functionality and the display of the calendar are not working as expected. I want to show the calendar horizontally like the example in the link, but it is currently dis ...

Detecting drag events between connected angular ui-trees is a complex yet achievable task

How can I trigger an action when an item is dragged from tree#1 to tree#2 and dropped? I want to make a specific HTTP call to save the transferred item. I have successfully implemented actions within one tree using the 'dropped' event, but strugg ...

Incorporate the ability to display a shape on a map when hovering over a table element, without the need to manually code a JavaScript function for every instance

I came across a script online that allows me to hover over text and have a shape appear on an imagemap. It's functional, but only works for a single instance. Is there a way to implement a JavaScript that handles individual instances so I don't h ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...