|
| 1 | +// |
| 2 | +// Minimum Coin Change Problem Playground |
| 3 | +// Compare Greedy Algorithm and Dynamic Programming Algorithm in Swift |
| 4 | +// |
| 5 | +// Created by Jacopo Mangiavacchi on 04/03/17. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +public enum MinimumCoinChangeError: Error { |
| 11 | + case noRestPossibleForTheGivenValue |
| 12 | +} |
| 13 | + |
| 14 | +public struct MinimumCoinChange { |
| 15 | + internal let sortedCoinSet: [Int] |
| 16 | + |
| 17 | + public init(coinSet: [Int]) { |
| 18 | + self.sortedCoinSet = coinSet.sorted(by: { $0 > $1} ) |
| 19 | + } |
| 20 | + |
| 21 | + //Greedy Algorithm |
| 22 | + public func changeGreedy(_ value: Int) throws -> [Int] { |
| 23 | + guard value > 0 else { return [] } |
| 24 | + |
| 25 | + var change: [Int] = [] |
| 26 | + var newValue = value |
| 27 | + |
| 28 | + for coin in sortedCoinSet { |
| 29 | + while newValue - coin >= 0 { |
| 30 | + change.append(coin) |
| 31 | + newValue -= coin |
| 32 | + } |
| 33 | + |
| 34 | + if newValue == 0 { |
| 35 | + break |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if newValue > 0 { |
| 40 | + throw MinimumCoinChangeError.noRestPossibleForTheGivenValue |
| 41 | + } |
| 42 | + |
| 43 | + return change |
| 44 | + } |
| 45 | + |
| 46 | + //Dynamic Programming Algorithm |
| 47 | + public func changeDynamic(_ value: Int) throws -> [Int] { |
| 48 | + guard value > 0 else { return [] } |
| 49 | + |
| 50 | + var cache: [Int : [Int]] = [:] |
| 51 | + |
| 52 | + func _changeDynamic(_ value: Int) -> [Int] { |
| 53 | + guard value > 0 else { return [] } |
| 54 | + |
| 55 | + if let cached = cache[value] { |
| 56 | + return cached |
| 57 | + } |
| 58 | + |
| 59 | + var potentialChangeArray: [[Int]] = [] |
| 60 | + |
| 61 | + for coin in sortedCoinSet { |
| 62 | + if value - coin >= 0 { |
| 63 | + var potentialChange: [Int] = [coin] |
| 64 | + potentialChange.append(contentsOf: _changeDynamic(value - coin)) |
| 65 | + |
| 66 | + if potentialChange.reduce(0, +) == value { |
| 67 | + potentialChangeArray.append(potentialChange) |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + if potentialChangeArray.count > 0 { |
| 73 | + let sortedPotentialChangeArray = potentialChangeArray.sorted(by: { $0.count < $1.count }) |
| 74 | + cache[value] = sortedPotentialChangeArray[0] |
| 75 | + return sortedPotentialChangeArray[0] |
| 76 | + } |
| 77 | + |
| 78 | + return [] |
| 79 | + } |
| 80 | + |
| 81 | + let change: [Int] = _changeDynamic(value) |
| 82 | + |
| 83 | + if change.reduce(0, +) != value { |
| 84 | + throw MinimumCoinChangeError.noRestPossibleForTheGivenValue |
| 85 | + } |
| 86 | + |
| 87 | + return change |
| 88 | + } |
| 89 | +} |
0 commit comments