jueves, 7 de abril de 2016

LINQ Recipe No. 2-6: Mathematics and Statistics - How to Find the Number of Currency Bills Required for a Given Amount?

Contents

1. Introduction
2. Key Words
3. Problem
4. Solution
5. Discussion
5.1 OrderByDescending()
5.2 ToList()
5.3 Where()
5.4 ForEach()
6. Practice: Number of Currency Bills Required for a Given Amount
7. Conclusions
8. Literature & Links

1. Introduction

We continue developing more LINQ recipes using the standard query operators and the tool LINQPad to test our solutions. This time, we will create a recipe to find the number of currency bills needed to fraction a given amount. As we will see in the practice section, the example code, at first glance, can be more extensive than a standard solution but it is more intuitive and expressive; and that is what matters in functional programming.

2. Key Words

  • Bill
  • Currency
  • Functional programming
  • LINQ
  • LINQPad
  • Standard query operator

3. Problem

Given the set of all currencies of a country, write a program that calculates the optimum number for each currency for a particular amount.

4. Solution

We can solve this problem using these standard query operators:
  • OrderByDescending()
  • ToList(), and
  • Where()
and the ForEach method from List<T> class.

5. Discussion

5.1 OrderByDescending()

The standard query operator OrderByDescending() sorts a sequence of elements in descending order ("Enumerable.OrderByDescending Method", 2016). For example, the array 

{100, 500, 50, 200, 1000, 2000, 5000, 100000, 10000, 50000}

will be sorted in the array descending order: 

{100000, 50000, 10000, 5000, 2000, 1000, 500, 200, 100, 50}

5.2 ToList()

The ToList() ("Enumerable.ToList(TSource)", 2016) method creates a list from an IEnumerable collection.

For example if we have the string array 

string[] msProducts = { "Windows", "Office 365", "Flight Simulator", "Edge", "Windows Explorer", "Notepad"};

with the ToList() method, we create a List<int< representing the lengths of each string object in the msProducts array:

List<int> lengths = msProducts.Select(msProduct => msProduct.Length).ToList();

5.3 Where()

The Enumerable.Where ("Enumerable.Where Method", 2016) method allows filter a sequence of elements depending on a given predicate.

List<int> lengths = msProducts.Select(msProduct => msProduct.Length).ToList();

lengths.Where(length => length == 7);

5.4 ForEach

ForEach ("List(T).ForEach", 2016) executes a series of actions on each element of a List<T> object.

With lengths object in the previous section, we can perform this:

lengths.ForEach(length => { Console.WriteLine (length);});

It will print out this values on the standard output:

7
10
16
4
16
7

6. Practice: Number of Currency Bills Required for a Given Amount

This example is an adaptation from Mukherjee (2014). The example shows us how to find the number of currency bills required for a given amount. This kind of operation is useful for those processes which involve cash: financial transactions, ATM operations, etc.

Here is the C# code solution:

// Currencies in Colombia:
int[] currencyValues = {100, 500, 50, 200, 1000, 2000, 5000, 100000, 10000, 50000};

// Amount to fraction in bills:
int amount = 254800;

// Map: Currency -> Number of bills:
Dictionary<int, int> change = new Dictionary<int, int>();

// Iterate over the bills and calculate its number for the amount:
currencyValues.OrderByDescending( currency => currency)
.ToList()
.ForEach( currency => {
change.Add(currency, amount / currency);
amount = amount % currency;
});

// Generate a printable result:
change.Where (currencyCount => currencyCount.Value != 0)
.Dump("Change");


The OrderByDescending() method sorts the currencyValues on descending order. Then the ordered bills are converted to a list by calling the ToList() method. Finally, the ForEach() method calculates the number of bills for each bill: the result is added to the change dictionary.


Once we execute this code in LINQPad, we get 
Bills for an amount
Illustration 1. Bills for an amount.

The Value column shows the number of bills in front each bill (Key column).

7. Conclusions

We have had the opportunity to learn how to calculate the number of bills required for a given amount. The LINQ is relatively simple to understand: it sorts the given currencies, converts the result to a list, and for each bill in the list determine the number of bills required for the given amount.

The next LINQ recipe will be focused on how to find moving averages.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
Enumerable.OrderByDescending Method (System.Linq) (2016, April 7). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.enumerable.orderbydescending(v=vs.110).aspx
Enumerable.ToList(TSource) Method (IEnumerable(TSource)) (System.Linq) (2016, April 7). Retrieved from: https://msdn.microsoft.com/en-us/library/bb342261(v=vs.110).aspx
List(T).ForEach Method (Action(T)) (System.Collections.Generic) (2016, April 7). Retrieved from: https://msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx
Enumerable.Where Method (System.Linq) (2016, April 7). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.enumerable.where(v=vs.110).aspx


V

No hay comentarios:

Publicar un comentario

Envíe sus comentarios, dudas, sugerencias, críticas. Gracias.