ATM Withdrawal Note Calculator in Java

mail@pastecode.io avatar
unknown
java
a month ago
2.7 kB
2
Indexable
Never
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;

// CREATED BY NGUYEN MINH HAI
public class Main {
    public static void main(String[] args) {
//        The ATM is having 2000 (5 notes), 500 (10 notes), 200 (10 notes), 100 (10 notes)
//
//        Input: Withdraw amount
//        Output: Number of each notes
//
//        Ex:
//        6000 - 3 notes of 2000
//        1600 - 3 notes of 500 and 1 note of 100
//        1650 - Not a valid amount
//        32000 - Amount not available in ATM
        Map<Integer, Integer> map = new LinkedHashMap<>();
        map.put(2000, 5);
        map.put(500, 10);
        map.put(200, 10);
        map.put(100, 10);

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter withdrawal amount: ");
        int amount = scanner.nextInt();

        if (amount > getTotalAmount(map)) {
            System.out.println("Amount not available in ATM");
            return;
        }
        Map<Integer, Integer> result = withdraw(amount, map);

        if (Objects.isNull(result)) {
            System.out.println("Not a valid amount");
            return;
        }

        int index = 0;
        int size = result.size();
        var str = new StringBuilder();
        for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
            if (entry.getValue() != 1) {
                str.append(entry.getValue()).append(" notes of ").append(entry.getKey());
            } else {
                str.append(entry.getValue()).append(" note of ").append(entry.getKey());
            }

            if (index < size - 1) {
                str.append( " and ");
            }
            index++;
        }

        System.out.println(str);
    }

    private static Map<Integer, Integer> withdraw(int amount, Map<Integer, Integer> map) {
        Map<Integer, Integer> result = new LinkedHashMap<>();
        for (int key : map.keySet()) {
            int count = Math.min(amount / key, map.get(key));

            if (count == 0) continue;

            result.put(key, count);
            amount -= count * key;

            if (amount == 0)
                return result;
        }

        if (amount > 0) {
            return null; // Invalid amount
        }

        return result;
    }


    private static int getTotalAmount(Map<Integer, Integer> map) {
        int total = 0;
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            total += entry.getKey() * entry.getValue();
        }
        return total;
    }

}
Leave a Comment