mercredi 14 février 2024

Implement the OptimalChange(long s): optimal way to give back a certain amount with the minimum number of coins and bills

 Stores are increasingly equipped with automated checkout machines.

Most of these machines accept payment only by credit card, despite the fact that a significant portion of consumers continue to pay for good with cash.

One of the problems presented by cash transactions is how to return change: what is the optimal way to give back a certain amount with the minimum number of coins and bills? It is an issue that each of us encounters on a daily basis and the problem is the same for automated checkout machines.

Try and find an optimal solution for returning change in a very specific case: when the machine contains only 2€ coins, 5€ bills ans 10€ bills.

To simplify the problem, imagine that all of these coins and bills are available in unlimited quantities.

Change is represented as a Change object.

This object has 3 properties: coin2, bill5, bill10 which represent the numbers of 2€ coins, 5€ bill and 10€ bills.

Implement the OptimalChange(long s) method which return a Change object.

The sum of coins and bills indicated in the Change object must be s.

If it is not possible to give back change, the method must return null.

=========================================


To implement the `OptimalChange` method in C#, you can use a greedy algorithm. Here's how you can do it: ```csharp public class Change { public long coin2 { get; set; } public long bill5 { get; set; } public long bill10 { get; set; } } public class ChangeProcessor { public static Change OptimalChange(long s) { // Initialize Change object with zeros Change change = new Change { coin2 = 0, bill5 = 0, bill10 = 0 }; // Validate input if (s <= 0) return null; // Calculate the number of 10€ bills change.bill10 = s / 10; s %= 10; // Calculate the number of 5€ bills change.bill5 = s / 5; s %= 5; // Calculate the number of 2€ coins change.coin2 = s / 2; s %= 2; // If there is any remainder, change cannot be given if (s != 0) return null; return change; } } class Program { static void Main(string[] args) { long amount = 27; // Example amount Change change = ChangeProcessor.OptimalChange(amount); if (change != null) { Console.WriteLine($"Change for {amount} euros:"); Console.WriteLine($"10€ bills: {change.bill10}"); Console.WriteLine($"5€ bills: {change.bill5}"); Console.WriteLine($"2€ coins: {change.coin2}"); } else { Console.WriteLine("Change cannot be given."); } } } ``` This code defines a `Change` class to represent the change with properties for the number of 2€ coins, 5€ bills, and 10€ bills. Then, there's a `ChangeProcessor` class with a static method `OptimalChange` which calculates the optimal change using a greedy approach. Finally, in the `Main` method, an example amount is passed to the `OptimalChange` method, and the resulting change is printed.

Aucun commentaire:

Enregistrer un commentaire