JS Implementation of the Coin Change Algorithm

I've been grappling with this algorithm for the past few days, but unfortunately I haven't been able to come up with a successful solution yet. The available solutions seem to be too advanced for my current level of understanding. This problem must be solved using conditionals only; recursion and dynamic programming are not allowed.

The challenge is to determine the minimum number of coins needed to make change using the following denominations: 1, 0.5, 0.2, 0.1, 0.05, 0.02, and 0.01.

Here is the input required:

- Price of an item

- Total amount paid by the customer

My initial thoughts are as follows:

let price = +gets();
let paidSum = +gets();
// 'gets' is used to receive numerical input
let change = paidSum - price;

I was thinking that I could use Math.floor to extract the integer part and subtract it from the total change, but I'm unsure how to proceed with the remaining sum.

Would using modulo help me determine if the remaining sum includes any of the remaining change values, allowing me to subtract sequentially until reaching zero?

I understand that my question might not be perfectly articulated, but I really am stuck on this problem. I've managed to tackle every other task except this one. Thank you for your help.

Answer №1

Take a simpler approach by reversing and mapping the denominations in cents, resulting in a new array that indicates the number of coins needed for each denomination.

const coinValues = [1, 2, 5, 10, 20, 50, 100]
const calculateChange = (amountInCents) => {
    return coinValues.reverse().map(coin => {
        let numOfCoins = Math.floor(amountInCents/coin)
        amountInCents -= numOfCoins * coin
        return numOfCoins
    }).reverse()
}

Answer №2

When dealing with the specific denominations you have provided, solving this problem is not as complex as the general change making problem. In this scenario, it is guaranteed that utilizing the largest denomination equal to or less than the amount due will always result in an optimal solution.

Therefore, there is no necessity for recursion or dynamic programming. A straightforward loop suffices.

For the purpose of simplicity, I am overlooking the initial step of determining the bill's price and the customer's payment amount. Ultimately, what truly matters is the change that needs to be returned to the customer. This code snippet addresses that by calculating the required change amount and providing the corresponding coins for repayment.

function getChange(amount) {
    amount *= 100; // Convert to number of cents
    var denominations = [1, 2, 5, 10, 20, 50, 100]; // cents
    var result = [];
    while (amount > 0) {
        var coin = denominations.pop(); // Get next greatest coin
        var count = Math.floor(amount/coin); // See how many times I need that coin
        amount -= count * coin; // Reduce the amount with that number of coins
        if (count) result.push([coin/100, count]); // Store count & coin
    }
    return result;
}

// I/O management

change.oninput = function () {
    var coins = getChange(this.value);
    result.textContent = coins.map(([coin, count]) => `${count} x $${coin}`).join(" + ");
};
To be paid to customer: <input id="change">
<div>Coins to pay: <span id="result"></span></div>

Answer №3

let coinsList;
let coinMap = {};
let result = {};


/* Function to extract whole number value of a coin - necessary due to
* javascript rounding behavior where 5.6 is treated as 6 in Math.round()
*/
function getWholeNumberCoinValue(x) {
    return (x * 10 - ((x * 10) % 10)) / 10;
}

// Function to calculate possible combinations of coins
function calculateCoins(inputAmount) {
    let largestPossibleCoin = 1;

    if (inputAmount) {
        coinsList.forEach((coin) => {
            if (inputAmount >= coin) {
                largestPossibleCoin = coin;
            }
        });
        let remainingChange = inputAmount % largestPossibleCoin;
        result[largestPossibleCoin] = getWholeNumberCoinValue(
            (inputAmount / largestPossibleCoin).toFixed(1)
        );
        if (remainingChange && inputAmount > 1) {
            calculateCoins(remainingChange);
        }

        return largestPossibleCoin;
    }
}

// Main function call to generate output
function computePossibleCoinCombinations(value) {
    if (isNaN(value) || +value <= 0) {
        console.log('Invalid input');
        return;
    } else {
        console.log('Possible coin combinations are:');
        value = +value;
    }

    coinsList = [1, 5, 10, 25];
    while (coinsList.length) {
        let largestCoin = calculateCoins(value) || 0;
        let outputStr = '';
        coinsList = coinsList.filter((coin) => coin < largestCoin);
        Object.keys(result).forEach((key) => {
            outputStr += `${result[key]} - ${key} cents; `;
        });
        console.log(outputStr);
        result = {};
    }
}


/*
Sample inputs:
 computePossibleCoinCombinations('89');
 computePossibleCoinCombinations(10);
 computePossibleCoinCombinations(0);
 computePossibleCoinCombinations('someString');
 computePossibleCoinCombinations(-10);
*/

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

Changing the URL dynamically based on user interaction with jQueryLet's leverage the power of

In continuation to my previous post, I am looking to dynamically change a URL based on the selected language. For example, if the current URL is href="../folder/Languages/English/test/test.html, clicking or selecting another language should update it to: h ...

What are the limitations when using React's forwardRef with Material UI's styled components?

While working with forwardRef and styled, I encountered a strange issue : "React Hook ... cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function." Here is an example: import { styled } ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Implementing dynamic title insertion into a popover element using jQuery

My goal is to assign a title to my popover object in a local project. I have already included the following files: bootstrap.css v4.2.1 jquery.min.js v2.2.0 bootstrap.min.js v4.2.1 popper.min.js v1.11.0 Initially, there was a basic button present. <i ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...

Transferring information from Child to Parent using pure Javascript in VueJS

I am familiar with using $emit to pass data from child components to parent components in VueJS, but I am trying to retrieve that value in a JavaScript function. Here is my situation: Parent Component created () { this.$on('getValue', func ...

Receiving unexpected results when returning a function within a React hook

I'm currently working on developing a custom React hook that will provide users with a function to execute. This hook is designed to generate a function internally. Check out this simplified example // fetch.js import { useEffect, useState} from &qu ...

Leveraging NodeJS to handle server-side tasks and operations

Background: I am exploring the use of NodeJS for a project that involves scraping and storing content in Mongo. This process needs to be automated according to a set schedule. In addition, I need functions that can extract items from the Mongo database, o ...

Unable to interpret data from JSON file

I have written the following code to read a JSON file. It is not throwing any errors, but I am receiving a null value in the variable: var myData = null; $.ajax({ type: 'GET', async: false, url: 'myJson.json', dataType: ...

When the form is submitted, I am unable to record the checkbox value

Hi, I have a question regarding submitting a form to the "/delete" route when a checkbox is checked. Although I am able to submit the form successfully, I am facing an issue retrieving the checkbox value that I assigned using ejs. Below are the relevant co ...

What are the key distinctions between an arrow function, a class, and a traditional function?

Is there a way to distinguish between the following three elements in ES6 using its reference? let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } For example: test(x) //=> ' ...

Guide on displaying a Custom 2D shape on both sides using three.js

As a beginner to three.js and 3D programming in general, I recently used three.js to draw a sector. However, I am facing an issue where I can only see the object in one direction but not in the opposite direction. It appears that the same phenomenon is h ...

Pair of dimensions painting with d3 version 4

I am having trouble converting my code from d3 v3 to d3 v4 Below is the original code snippet: var brush = d3.svg.brush() .x(x) .y(y) .on("brushstart", brushstart) .on("brush", brushmove) .on("brushend", brushend); However ...

The React component fails to inherit any props that are passed to it when it is rendered using a logical operator

I'm facing an issue with a component that doesn't seem to receive any props when I use a logical operator in conjunction with it. Oddly enough, if I render the component without the conditional statement, everything works fine. But as soon as I a ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

The information window is malfunctioning on Google Maps

I created buttons that are linked to specific locations on a map and they seem to be functioning, although not in the most efficient way. However, when attempting to add an info window to appear on the marker, it does not work as expected. I am unsure of ...

What is the smallest server.js file needed to run a react/redux application?

I have successfully configured my project using webpack and babel for ES6 transpilation with the specified presets: { "presets": ["react", "es2015", "stage-1"] } My webpack production configuration is structured as follows: var path = require('pa ...

Steps for triggering a click event on a div with a button role within a class containing multiple elements

Can anyone help me figure out how to auto-click every button in Instagram's "hide story from" settings using console? I tried the following code: for (let i = 0; i < 300; i++) { document.getElementsByClassName('wbloks_1')[i] ...

What are some methods for creating a Venn Diagram that includes data within each section using SVG, CSS, or Canvas?

I am attempting to replicate this visual representation using pure SVG, CSS, or Canvas drawing. So far, I have successfully created three circles that overlap and placed a label in the center of each one. However, I'm facing challenges when it comes t ...

What is the reason for the request body being undefined?

I have a JavaScript file named index.js that contains: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const db = require('./db'); const movieRouter = re ...