Monday, May 7, 2012

Coin problem with greedy approach

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: uchan
 * Date: 5/6/12
 * Time: 9:41 PM
 * To change this template use File | Settings | File Templates.
 */
public class CoinCalc {

    private static int[] coinArray = new int[]{100, 50, 10, 5, 2, 1};

    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Please give the amount as an argument");
            return;
        }
        try {
            int amount = Integer.parseInt(args[0]);
            Map<integer, integer> coinSelectionMap = getCoins(amount);
            System.out.println("CoinSelection = " +  coinSelectionMap);
        } catch (NumberFormatException e) {
            System.err.println("Please specify amount as an integer");
        }
    }

    private static Map<integer, integer> getCoins(int amount) {
        Map<integer, integer> coinSelection = new LinkedHashMap<integer, integer>();
        int rest = amount;

        for (int coinValue : coinArray) {
            int numberOfCoins = rest / coinValue;

            if (numberOfCoins == 0) {
                continue;
            }
            rest = rest % coinValue;
            coinSelection.put(coinValue, numberOfCoins);

            if (rest == 0) {
                break;
            }
        }
        return coinSelection;
    }
}

No comments:

Post a Comment