コード例 #1
0
        /// <summary>
        /// Create the result table of all possible changes for the given coinInventory.
        /// </summary>
        /// <param name="coinInventory">The inventory of all the coins to make the change.</param>
        /// <param name="change">The given change required.</param>
        /// <returns>Return <c>ResultTable</c> if result is found else null.</returns>
        ///
        private ResultTable CreateResultTable(IList <int> orderedDenomination, IReadOnlyDictionary <int, int> coinInventory, int change, int smallestDenomination = 0)
        {
            ResultTable result = new ResultTable(orderedDenomination.Count, change);

            for (int i = 0; i < orderedDenomination.Count; i++)
            {
                var availableCoin = coinInventory[orderedDenomination[i]];
                for (int j = change; j >= smallestDenomination; j--)
                {
                    if (result.HasResult(j))
                    {
                        continue;
                    }

                    int k = 1; // number of current coin type needed to make up the change (j)
                    int kDenominationTotal = orderedDenomination[i];
                    while (k <= availableCoin && j - kDenominationTotal >= 0)
                    {
                        // it is possible to make up the change (j) using current denomination + previous results
                        if (result.HasResult(j - kDenominationTotal))
                        {
                            result[i, j] = k;
                            if (j == change)
                            {
                                return(result);
                            }
                            break;
                        }
                        kDenominationTotal = ++k * orderedDenomination[i];
                    }
                }
            }
            return(null);
        }