地图中的贪婪算法java

问题描述 投票:0回答:2

我正在用Java开发ATM模拟器。项目中的总体模式是Command。所以我有4个命令-getInfo,deposit,withdraw和exit。

我在撤回方法中实现贪婪算法时遇到问题。如果我们退出,则第一个Integer为“面额”,第二个Integer为“金额”,则应该返回Map。

public Map<Integer, Integer> withdrawAmount(int expectedAmount) 

因此,它将期望的金额作为参数,并且必须从ATM中以尽可能少的票据金额将其减去。

   public class CurrencyManipulator
    {
// denominations is a map where each denomination and it's quantity stored
        private String currencyCode;
        private Map<Integer, Integer> denominations = new HashMap<>();

        public String getCurrencyCode()
        {
            return currencyCode;
        }

    public CurrencyManipulator(String currencyCode)
    {
        this.currencyCode = currencyCode;
    }

    public void addAmount(int denomination, int count)
    {
        if (denominations.containsKey(denomination))
        {
            denominations.put(denomination, denominations.get(count) + count);
        } else
        {
            denominations.put(denomination, count);
        }
    }

    public int getTotalAmount()
    {
        int sum = 0;
        for (Map.Entry<Integer, Integer> pair : denominations.entrySet())
        {
            sum = pair.getKey() * pair.getValue();
        }
        return sum;
    }

    public boolean hasMoney()
    {
        return denominations.size() != 0;
    }

    public boolean isAmountAvailable(int expectedAmount)
    {
        return expectedAmount <= getTotalAmount();
    }

     public Map<Integer, Integer> withdrawAmount(int expectedAmount) throws NotEnoughMoneyException
    {


    }
} 

因此,如果要求的金额“ expectedAmount”高于ATM中的可用货币,则我需要此方法来返回地图或引发异常。

如果我们收取$ 600,则可能是-三张钞票:$ 500 + $ 50 + $ 50或$ 200 + $ 200 + $ 200,首选选项是$ 500 + $ 50 + $ 50例如,您必须给$ 600自动柜员机的帐单数量如下:

500-2

200-3

100-1

50-12

结果应该是:

500-1

100-1

这是我想出的:

public Map<Integer, Integer> withdrawAmount(int expectedAmount) throws NotEnoughMoneyException
    {

        denominations.put(50,1);
        denominations.put(500,1);
        denominations.put(200,3);
        HashMap<Integer, Integer> map = new HashMap<>();
        TreeMap<Integer, Integer> sortedMap = new TreeMap<>(Collections.reverseOrder());
        sortedMap.putAll(denominations);
        ArrayList<Integer> bills = new ArrayList<>();
        bills.addAll(sortedMap.keySet());


        int num;

        for (int i = 0; i < bills.size(); i++)
        {
            if (bills.get(i) <= expectedAmount)
            {
                num = expectedAmount / bills.get(i);
                map.put(bills.get(i), num);
                expectedAmount -= num * bills.get(i);
            }
        }
        System.out.println(map);
        return map;
    }

它返回所需票据及其数量的地图。

现在我的问题是..我如何将其与我拥有的“教派”地图进行比较,并从中减去新地图?

我正在用Java开发ATM模拟器。项目中的总体模式是Command。所以我有4个命令-getInfo,deposit,withdraw和exit。我在实施贪婪时遇到问题...

java algorithm dictionary greedy
2个回答
0
投票

如果有人需要,似乎是工作代码


0
投票

另一种解决方案。如果使用TreeMap

© www.soinside.com 2019 - 2024. All rights reserved.