Developing a JavaScript program for ATMs that can efficiently handle and dispense money in the fewest number of notes possible

When a certain amount is entered, the code should be capable of handling figures up to 20000. For instance, if the input amount is 2600 with a card balance of 3000, the output will be as follows: New Balance - 400 Notes: 2000 * 1 500 * 1 100 * 1

Only three banknotes are allowed: 2000, 500, and 100, and there is a cash limit of 20000.

I am relatively new to the world of JavaScript and struggling to write the necessary code. Can someone please assist me?

var h = 5;
var f = 2;
var t = 1;

// More code snippets here...

Apologies for the simple program, but I would greatly appreciate if someone could provide a solution in TypeScript code, returning the required denomination in an array. Thank you!

Answer №1

function separateNotes(amount) {
  let hundredCount = 0;
  let fiftyCount = 0;
  let twentyCount = 0;

  while (amount >= 20) {
    if (amount >= 100 && ((amount % 100) % 50 === 0 || (amount % 100) % 20 === 0)) {
      amount -= 100;
      hundredCount++;
    } else if (amount >= 50 && ((amount % 50) % 100 === 0 || (amount % 50) % 20 === 0)) {
      amount -= 50;
      fiftyCount++;
    } else {
      amount -= 20;
      twentyCount++;
    }
  }

  return [hundredCount, fiftyCount, twentyCount];
}

console.log(separateNotes(230));
console.log(separateNotes(250));

Answer №2

amtArray = [2000, 500, 100];  // array containing denominations to find

 for (let i = 0; i < this.amtArray.length; i++) {
            this.resultArray.push(Math.floor(total / this.amtArray[i]));
            // Calculate new total
            total = total % this.amtArray[i];
        }
        var twothousands_notes = this.resultArray[0];
        var fivehundred_notes = this.resultArray[1];
        var hundred_notes = this.resultArray[2];

        console.log('Calculated amounts: ' + '100 : ' +
            hundred_notes + '   500 :  ' +
            fivehundred_notes + '  2000 :  ' +
            twothousands_notes);

You can customize the logic based on the given amount.

Hope this explanation is helpful! :)

Answer №3

Here is a convenient solution for all your scenarios:

function dispenseCase (inputAmount) {
 var notes = [];
 var balance = 3000;

  if(inputAmount !== 0 && inputAmount % 100 == 0 && inputAmount <= balance) {
    var notes2000 = Math.round(inputAmount / 2000);
    var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
    var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);

   notes.push(notes2000);
   notes.push(notes500);
   notes.push(notes100);

   console.log("Your account balance = ", balance - inputAmount);
   console.log(notes);
  }
  else if (inputAmount > balance) {
   console.log("Insufficient funds in your account");
  }
  else if ( inputAmount % 100 != 0 || inputAmount < 100 ) {
   console.log( "Invalid amount entered, amount must be multiples of 100");
}
}

dispenseCase(2600);

Answer №4

Creating a program in JavaScript to calculate ATM denominations.

This program will determine the minimum number of notes needed to make up a specified amount, starting from the highest denomination to the lowest.

function countCurrency(amount) {
  var notes = [2000, 500, 200, 100];
  var noteCounter = [0, 0, 0, 0];

  for (var i = 0; i < 4; i++) {
    if (amount >= notes[i]) {
      noteCounter[i] = Math.floor(amount / notes[i]);
      amount = amount - noteCounter[i] * notes[i];
    }
  }
  // Display notes denomination
  console.log("Denomination Count:");
  for (var j = 0; j < 4; j++) {
    if (noteCounter[j] !== 0) {
      console.log(notes[j] + " : " + noteCounter[j]);
    }
  }
}

countCurrency(3300);

For a live demo of the program, click here

Answer №5

If you input an amount, this code will calculate the number of notes in denominations of 2000, 500, and 100 needed to dispense that amount.

function calculateNotes (enteredAmount) {
 var notes = [];

  if(enteredAmount !== 0) {
    var notes2000 = Math.round(enteredAmount / 2000);
    var notes500 = Math.round((enteredAmount - (notes2000 * 2000)) / 500 );
    var notes100 = Math.round((enteredAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);

   notes.push(notes2000);
   notes.push(notes500);
   notes.push(notes100);

   console.log(notes);
  }
}

calculateNotes(2600);

Hopefully, this explanation clarifies the process for you.

Answer №6

//ATM Cash Denominations //Cash Input Value Already been Provided in this method // You may use a input stream method to input a user input value

public class ATMWithdrawal
{
 public static void main(String args[])//throws IOException
 {

 int notes[]={200,100,50,20,10}; //storing all the denominations in an array
 int amount = 500;

 int copy=amount; //Making a copy of the amount
 int totalNotes=0,count=0;

 System.out.println("\nATM CASH DENOMINATIONS: \n");

 for(int i=0;i<5;i++) //Since there are 5 different types of notes, hence we check for each note.
 {
 count=amount/notes[i]; // counting number of notes[i] notes
 if(count!=0) //printing that denomination if the count is not zero
 {
 System.out.println(notes[i]+"\tx\t"+count+"\t= "+notes[i]*count);
 }
 totalNotes=totalNotes+count; //finding the total number of notes
 amount=amount%notes[i]; //finding the remaining amount whose denomination is to be found
 }

 System.out.println("--------------------------------");
 System.out.println("TOTAL\t\t\t= "+copy); //printing the total amount
 System.out.println("--------------------------------");
 System.out.println("Total Number of Notes\t= "+totalNotes); //printing the total number of notes
 }
} 

Answer №7

let sumToDenominate=Math.floor(Math.random() * 100);
let billsValues = [100, 50, 20, 10, 5,1];

let restAfterDenomination = [];
let billsNumber = [];



function denomination(sum, billsValues) {



printInitialValue( sumToDenominate, billsValues);

initializeArray( sumToDenominate, billsValues);


for (let i = 1; i <= billsValues.length; i++) {

    if (restAfterDenomination[i - 1] > 0 || restAfterDenomination < billsNumber[i]) {

        billsNumber.push(Math.floor(restAfterDenomination[i - 1] / billsValues[i]));

        console.log(`bill's number of `, billsValues[i], "=>", billsNumber[i]);

        restAfterDenomination.push(restAfterDenomination[i - 1] - (billsNumber[i] * billsValues[i]));


    } else {
        console.log(`rest is less than smallest bill or equal to 0`);
        billsNumber.push(0);
        // break;
    }
}



}

function printInitialValue(amount, billsValue) {
console.log("Denomination sumToDenominate: ", amount);

console.log("____________");
for (const logEntry of billsValue) {
    console.log(logEntry);
}
console.log("__________");
}

function initializeArray(amount, billsValues) {


billsNumber.push(Math.floor(amount / billsValues[0]));

console.log(`bill's number of`, billsValues[0], "=>", billsNumber[0]);

restAfterDenomination.push(amount - (billsNumber[0] * billsValues[0]));


denomination(sumToDenominate,billsValues);

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

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

In Chrome, there is a conflict between the screen width when using `position: absolute` and `position: fixed` if there is vertical

I'm in the process of developing a website with a video banner set to fixed positioning in the background, and a div that has absolute positioning covering part of the video on the bottom half. However, I've encountered an issue - when I add this ...

Using a jQuery prompt to ensure data is saved when leaving the page

Is there a way to prompt users to save data on specific pages before they leave them? I'm thinking of using the jQuery UI dialog box. I understand that I can utilize the onbeforeunload event to recognize when a user is about to leave the current page, ...

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

Missing folders in npm package

After successfully creating and publishing a private npm package, I noticed an inconsistency in the file structure when installing it on another project: Library.Util | |__index.js | |__package.json The original file structure of the package includes a t ...

Transform array of elements from type T1 to element in the array to type T2

Here is a Typescript class I am working with: export class Envelope<T> { result: T; constructor(result: T) { this.result = result; } } I'm trying to convert Envelope<RecentPostResponse[]> to Observable<PostModel[]>: getP ...

Looking for a way to create a regular expression that can parse an email response containing the newline character?

Do you need help parsing only the most recent reply from the email thread below? For example, Hello Nikhil Bopora,↵↵Just to give a brief, I am in process of building an alternate e-lending↵platform. I tried using the general regex /[\s]*([&bsol ...

Javascript and the output of Ajax request

I'm facing an issue with my JavaScript files interacting with the response from an ajax request. It seems that the JavaScript is unable to read the response from the ajax call. My question is, how can I get my jQuery plugin to access the classes in t ...

"Compilation error: 'not defined' is not recognized, 'no-undef

I am currently working on a login form that will fetch values from this API: However, the password field is currently empty, allowing any password to be accepted. This results in the error: Failed to compile 'userName' is not defined no-undef; ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...

Changing Objects in an Array by Leveraging the Reduce Method with the Spread Operator in JavaScript

Currently delving into the world of JavaScript and decided to put the Spread Operator and reduce() method to the test. Here's an example: const numArray = [1, 6, 9, 4, 21, 8, 15]; const sumEvenOdd = numArray.reduce((acc, current) => current % ...

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

Maintain hook varieties during implementation of array deconstruction

I have been developing a straightforward hook to export animation helper and element reference. import { gsap } from 'gsap'; import { useRef } from 'react'; export function useTween<R extends gsap.TweenTarget>(vars: gsap.TweenVar ...

Challenges arise when dealing with generics in TypeScript

I'm a beginner in TypeScript and I'm trying to write a method with a generic type argument similar to what you can do in .Net. Here's the code snippet I've been working on: class TestObject { Id: number; Truc: string; Machin: str ...

Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function: var string= string.split(' ').join(''); For example, if I input the String: Hello how are you, it should become Hellohowareyou My approach avoids using ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

What is the simplest method for converting a large JSON array of objects into an object containing the same data under the key "data" in TypeScript?

What is the most efficient method for converting a large JSON array of objects into an object with a key named "data" using TypeScript: Original Format: [ { "label":"testing", "id":1, "children":[ { "label":"Pream ...

Typescript's Integrated Compatibility of Types

One important concept I need to convey is that if one of these fields exists, then the other must also exist. When these two fields are peers within the same scope, it can be challenging to clearly communicate this connection. Consider the example of defi ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...