Created
January 16, 2019 16:47
-
-
Save AustinBCole/20ea45282e40352c5635dc23cdc66d20 to your computer and use it in GitHub Desktop.
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
Assumptions: | |
I should guard against any negative doubles. | |
Test Cases: | |
1.00 --> "Your change is 1 dollar." | |
1.01 --> "Your change is 1 dollar and 1 penny." | |
1.41 --> "Your change is 1 dollar and 1 quarter and 1 dime and 1 nickel and 1 penny." | |
Implementation: | |
I will start by writing some if statements inside of a while loop. The if statements will check if I can subtract 1.00, .25, | |
.10, .05 and .01, beginning with the largest. I will then subtract the number from the variable within which I will save the | |
amount of change due. I will also += the appropriate variable containing the number of change items that the if statement | |
indicates. After doing this I will work on making the code more concise and refined. | |
Code: | |
func makeChange(forAmount: Double, withCost: Double) -> String { | |
guard forAmount > withCost, forAmount > 0, withCost >= 0 else { | |
return "You are not due any change." | |
} | |
var dollars = 0 | |
var quarters = 0 | |
var dimes = 0 | |
var nickels = 0 | |
var pennies = 0 | |
var changeDue = forAmount - withCost | |
var dollarsString = "" | |
var quartersString = "" | |
var dimesString = "" | |
var nickelsString = "" | |
var penniesString = "" | |
while changeDue != 0 { | |
if changeDue >= 1.00 { | |
changeDue -= 1.00 | |
dollars += 1 | |
} | |
else if changeDue >= 0.25 { | |
changeDue -= 0.25 | |
quarters += 1 | |
} | |
else if changeDue >= 0.10 { | |
changeDue -= 0.10 | |
dimes += 1 | |
} | |
else if changeDue >= 0.05 { | |
changeDue -= 0.05 | |
nickels += 1 | |
} | |
else if changeDue >= 0.01 { | |
changeDue -= 0.01 | |
pennies += 1 | |
} | |
} | |
if dollars != 1 { | |
dollarsString = "\(dollars) dollars" | |
} else { | |
dollarsString = "\(dollars) dollar" | |
} | |
if quarters != 1 { | |
quartersString = "\(quarters) quarters" | |
} else { | |
quartersString = "\(quarters) quarter" | |
} | |
if dimes != 1 { | |
dimesString = "\(dimes) dimes" | |
} else { | |
dimesString = "\(dimes) dime" | |
} | |
if nickels != 1 { | |
nickelsString = "\(nickels) nickels" | |
} else { | |
nickelsString = "\(nickels) nickel" | |
} | |
if dollars != 1 { | |
penniesString = "\(pennies) pennies" | |
} else { | |
penniesString = "\(pennies) penny" | |
} | |
return "Your change is \(dollarsString), \(quartersString), \(dimesString), \(nickelsString) and \(penniesString)." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment