/**
* Cash Register
*
* Description
* The goal of this challenge is to design a cash register program. You will be
* given two decimal numbers. The first is the purchase price (PP) of the item.
* The second is the cash (CH) given by the customer. Your register currently has
* the following bills/coins within it:
* <table>
* <tr><td>PENNY</td><td>.01</td></tr>
* <tr><td>NICKEL</td><td>.05</td></tr>
* <tr><td>DIME</td><td>.10</td></tr>
* <tr><td>QUARTER</td><td>.25</td></tr>
* <tr><td>HALF DOLLAR</td><td>.50</td></tr>
* <tr><td>ONE</td><td>1.00</td></tr>
* <tr><td>TWO</td><td>2.00</td></tr>
* <tr><td>FIVE</td><td>5.00</td></tr>
* <tr><td>TEN</td><td>10.00</td></tr>
* <tr><td>TWENTY</td><td>20.00</td></tr>
* <tr><td>FIFTY</td><td>50.00</td></tr>
* <tr><td>ONE HUNDRED</td><td>100.00</td></tr>
* </table>
* The aim of the program is to calculate the change that has to be returned to
* the customer.
*
* Input
* Your program should read lines of text from standard input. Each line contains
* two numbers which are separated by a semicolon. The first is the Purchase price (PP)
* and the second is the cash(CH) given by the customer.
*
* Output
* For each line of input print a single line to standard output which is the change
* to be returned to the customer. In case the CH < PP, print out ERROR. If CH == PP,
* print out ZERO. For all other cases print the amount that needs to be returned,
* in terms of the currency values provided. The output should be alphabetically
* sorted.
*
* Example
* 15.94;16.00 => NICKEL,PENNY
* 17;16 => ERROR
* 35;35 => ZERO
* 45;50 => FIVE
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Set;
import java.util.SortedMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.nio.charset.StandardCharsets;
public class Main {
private static final SortedMap
<Double, String
> coins
;
static {
coins
= new java.
util.
TreeMap<Double, String
>( (d1,d2
) -> (d1
>d2
)? -1 : (d1
<d2
)?1:0 ); coins.put(0.01d,"PENNY");
coins.put(0.05d,"NICKEL");
coins.put(0.10d,"DIME");
coins.put(0.25d,"QUARTER");
coins.put(0.50d,"HALF DOLLAR");
coins.put(1.00d,"ONE");
coins.put(2.00d,"TWO");
coins.put(5.00d,"FIVE");
coins.put(10.00d,"TEN");
coins.put(20.00d,"TWENTY");
coins.put(50.00d,"FIFTY");
coins.put(100.00d,"ONE HUNDRED");
}
/**
* Iterate through each line of input.
*/
while ((line = in.readLine()) != null) {
double[] inputs
= Stream.
of(line.
split(";")).
mapToDouble(Double::valueOf
).
toArray();
if (inputs[1] < inputs[0]) {
continue;
} else if (inputs[1] == inputs[0]) {
continue;
}
Set<String> changes = new java.util.HashSet<>();
double remains = inputs[1] - inputs[0];
for (Double coin
: coins.
keySet()) { double newRemains = remains % coin;
if (newRemains != remains) {
remains = newRemains;
changes.add(coins.get(coin));
}
}
System.
out.
println(changes.
stream().
sorted().
collect(Collectors.
joining(","))); }
}
}