Last active
July 28, 2023 18:29
-
-
Save colemancda/7cda5be14e14dff26b8bb025866763a1 to your computer and use it in GitHub Desktop.
Swift Register Command LIne
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
while let line: String = readLine() { | |
print(processInput(line)) | |
} | |
func processInput(_ line: String) -> String { | |
let components = line.components(separatedBy: ";") | |
guard components.count == 2, | |
let price = Float(components[0]), | |
let cash = Float(components[1]) else { | |
return "Invalid input" | |
} | |
// input validation | |
guard cash > price else { | |
if cash == price { | |
return "ZERO" | |
} else { | |
return "ERROR" | |
} | |
} | |
let change = registerChange(price: price, cash: cash) | |
assert(change.isEmpty == false) | |
return change.reduce("", { $0 + ($0.isEmpty ? "" : ",") + $1.print }) | |
} | |
func registerChange(price: Float, cash: Float) -> [Coin] { | |
guard price != cash, price < cash else { | |
return [] | |
} | |
var changeValue = cash - price | |
var coins = [Coin]() | |
while let coin = largestDenomination(for: changeValue) { | |
changeValue -= coin.rawValue | |
coins.append(coin) | |
} | |
return coins | |
} | |
func largestDenomination(for change: Float) -> Coin? { | |
Coin.allCases | |
.sorted(by: { $0.rawValue > $1.rawValue }) | |
.first(where: { $0.rawValue <= change }) | |
} | |
enum Coin: Float, CaseIterable { | |
case penny = 0.01 | |
case nickel = 0.05 | |
case dime = 0.10 | |
case quarter = 0.25 | |
case half = 0.50 | |
case one = 1.00 | |
case two = 2.00 | |
case five = 5.00 | |
case ten = 10.00 | |
case twenty = 20.00 | |
case fifty = 50.00 | |
case oneHundred = 100.00 | |
} | |
private extension Coin { | |
var print: String { | |
switch self { | |
case .penny: return "PENNY" | |
case .nickel: return "NICKEL" | |
case .dime: return "DIME" | |
case .quarter: return "QUARTER" | |
case .half: return "HALF DOLLAR" | |
case .one: return "ONE" | |
case .two: return "TWO" | |
case .five: return "FIVE" | |
case .ten: return "TEN" | |
case .twenty: return "TWENTY" | |
case .fifty: return "FIFTY" | |
case .oneHundred: return "ONE HUNDRED" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment