C#计算美元面额

时间:2011-04-09 01:48:02

标签: c# arrays algorithm

这是一个代码,可以找到获得87种不同账单的总方式。我想知道如何改变这个以获得最少量的账单(4 - 20,1 - 5,2 - 1)而不是每一种方式。任何帮助将不胜感激。

int target = 87;
int[] dollarSizes = { 1, 5, 10, 20 };
int[] ways = new int[target+1];
ways[0] = 1;

for (int i = 0; i < dollarSizes.Length; i++) {
    for (int j = dollarSizes[i]; j <= target; j++) {
        ways[j] += ways[j - dollarSizes[i]];
    }
}

4 个答案:

答案 0 :(得分:2)

您想要跟踪的是您能够以多快的速度到达目标。所以给定20,10,5,1面额,代码在psuedo

中看起来像这样
int initial = 87;             initial  twenties  tens   fives   ones
int twenties = initial / 20;    87        4
initial = initial % 20;          7        4    
int tens = initial / 10;         7        4       0
initial = initial % 10;          7        4       0
int fives = initial / 5;         7        4       0       1
initial = initial % 5;           2        4       0       1
int ones = initial;              2        4       0       1       2

正如您所看到的,有很多重复的逻辑,因此可以从循环(我们最大值 开始)提供。

答案 1 :(得分:2)

        int target = 87;
        int[] dollarSizes = { 100, 20, 10, 5, 1 };
        int[] counts = { 0, 0, 0, 0, 0 };

        int remainder = target;
        int bill = 0;
        while (remainder > 0)
        {
            counts[bill] = remainder / dollarSizes[bill];
            remainder -= counts[bill] * dollarSizes[bill];
            bill++;
        }

答案 2 :(得分:0)

首先使用最高账单计算。如果新金额太大,请不要添加该帐单,然后转到下一个美元大小:

class Program
{
    static void Main(string[] args)
    {
        var target = 87;
        var current = 0;
        var dollarSizes = new[] { 1, 5, 10, 20 }.OrderByDescending(x => x); // just make sure they're descending.
        var bestWay = new List<int>();

        foreach (var dollarSize in dollarSizes)
        {
            while (current + dollarSize <= target)
            {
                current += dollarSize;
                bestWay.Add(dollarSize);
            }

            if (current == target)
                break;
        }

        foreach (var dollar in bestWay)
        {
            Console.Write("{0}, ", dollar);
        }

        Console.ReadLine();
    }
}

答案 3 :(得分:0)

public static int MakeChange(int amount)
{
    if (amount < 0)
        throw new ArgumentOutOfRangeException("Amount should be greater than 0.");

    int[] availableBills = { 20, 10, 5, 1 };
    int[] availableBillCounts = { 0, 0, 0, 0 };
    int iterator = 0;
    int reminder = amount;

    while (reminder > 0)
    {
        availableBillCounts[iterator] = reminder / availableBills[iterator];
        reminder = amount % availableBills[iterator];
        iterator++;
    }

    return availableBillCounts.Sum();
}