Mostrando entradas con la etiqueta English. Mostrar todas las entradas
Mostrando entradas con la etiqueta English. Mostrar todas las entradas

miércoles, 13 de julio de 2016

LINQ Recipe No. 2-17: Collections - How to Find the Larger or Smaller Value of Sequences at Each Element Index

Contents

1. Introduction
2. Keywords
3. Problema
4. Solution
5. Discussion
5.1 Zip() standard query operator
6. Pratice: Denoting Bidding Values
7. Conclusions
8. Literature & Links

1. Introduction

With this new LINQ recipe the programmer will learn how to find the larger or smaller value from several given sequences. These sequences have the same length and are composed of numeral values. Particularly, the programmer is going to use, once again, the Zip() standard query operator from LINQ to accomplish this computation. In the practice section, the reader will know how to find the maximum and minimum bid values from the given sequences. LINQ is amazing!

2. Keywords

  • Collection
  • LINQ
  • Sequence
  • Standard query operator
  • Zip()

3. Problem

Find the minimum or maximum value of several sequences at each element index.

4. Solution

In LINQ we find the Zip() standard query operator to apply some specified function to a sequence of elements; the function uses each index as input values.

5. Discussion

5.1 Zip() standard query operator

Zip() is a standard query operator; it's useful to apply some specified function to each element index of a sequence. Visually, it can viewed as 
Zip visual operation schema
Illustration 1. Zip() visual operation schema.
Notice that each index from seq1 has its corresponding index on seq2: the function operates over each index.

To exemplify it, this code concatenates the symbol and literal representations for numbers: 

int[] numbers = { 1, 2, 3 };
string[] words = { "One", "Two", "Three"};

var numbersAndWords = numbers.Zip(words, (n, w) =>
String.Format("{0} - {1}", n, w));

numbersAndWords.Dump("Numbers and Words");

Once executed in LINQPad, this is the result: 
Zip() example
Illustration 2. Zip() example.

6. Practice: Denoting Bidding Values

Suppose we have two collections to represent the bidding values for different items.

The purpose with this recipe is to learn how, by means of LINQ, to find the smaller and larger of bidding values.

LINQ file MinMaxBids.cs [Mirror 1][Mirror 2]: 
Lines 2 and 3 define two list of bid values as integer elements. Next, lines 6-8, we call Zip() function to find the maximum bids from sequence's indexes. Observe how the Math.Max() function is used to find the maximum between the two parameters bid1 and bid2.


Analogally, lines 11-13, compute the Math.Min() function to find the minimum of the two parameters -bid1 and bid2.


The output in LINQPad: 
Minimum and maximum bids
Illustration 1. Minimum and maximum bids.

An extended version of this solution consists on multiple bid sequences (it's a generalized approach): 

LINQ file MinMaxBidsGeneralApproach.cs [Mirror 1][Mirror 2]: 

Four sequences are defined to contain bid values (lines 2-5). All these sequences are added to a list of lists (lines 8-12). Its purpose is to find the smaller and larger bid values using the Aggregate ("Enumerable.Aggregate(TSource) Method", 2016); basically, what this method does is apply an accumulator over a sequence.


Once executed, this is the resultant output in LINQPad: 
Minimum and maximum bids (general approach)
Illustration 3. Minimum and maximum bids (general approach).
Video tutorial: 

7. Conclusions

We have used the Zip() as programmatic mechanism to find the smaller or larger values from two sequences. This knowledge is useful for many applications which require this kind of computation for some type of values.


Next LINQ recipe is going to explain how to generate Armstrong Numbers and similar number sequences.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
Enumerable.Zip(TFirst, TSecond, TResult) Method (System.Linq) (2016, julio 13). Retrieved from: https://msdn.microsoft.com/en-us/library/dd267698%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396
Enumerable.Aggregate(TSource) Method (IEnumerable(TSource), Func(TSource, TSource, TSource)) (System.Linq) (2016, julio 13). Retrieved from: https://msdn.microsoft.com/en-us/library/bb548651(v=vs.110).aspx


O

jueves, 7 de julio de 2016

LINQ Recipe No. 2-16: How to Pick Every nth Element from a Collection

Contents

1. Introduction
2. Keywords
3. Problem
4. Solution
5. Discussion
5.1 Range(int, int) method
5.2 Skip() method
6. Practice: Picking Every nth Element from a Collection
7. Conclusions
8. Literature & Links

1. Introduction

A task like element selection, or more particularly pick every nth element, from a collection is a common problem that frequently appears in other problems such as randomizing, listing, or load distribution. In this LINQ recipe will demonstrate to the programmer how to write an idiomatic LINQ program to query a collection for finding every nth element.

2. Keywords

  • Collection
  • LINQ
  • List
  • Load distribution
  • Query

3. Problem

Pick every nth element from a given sequence (without dividing the index to determine whether to include an element from the collection).

4. Solution

First, it's possible to divide the sequence's count property by the nth element, and then use Skip() method to bypass a specified number of elements in the sequence.

5. Discussion

5.1 Range(int, int) method

Range() method generates a sequence of number for a range. ("Enumerable.Range Method", 2016). For example: 

IEnumerable<int> cubes = Enumerable.Range(1, 10).Select( x => x * x * x);

Here, Range generates the range of numbers from 1 to 10 as counting, i.e., 10 numbers. Then Select() produces the 3rd power for each number from 1 to 10.

5.2 Skip() method

This method is used to bypass a given number of elements, and it returns the remaining elements of the sequence ("Enumerable.Skip(TSource)", 2016).

int[] grades = {53, 61, 97, 91, 89, 71};

IEnumerable lowerGrades = grades.OrderByDescending(g => g)
.Skip(3);

What we get with this expression is lower grades: in the first place, the sequence is sorted in descending order, then with Skip(3) the higher grades -97, 91, and 89- are skipped.

6. Practice: Picking Every nth Element from a Collection

Now it's time to write an idiomatic LINQ query in LINQPad to pick every nth element in a sequence.

With int n = 10; (line 2) we specify the nth element: in this case we will pick every 10th element. In line 5 we request a list of 100 numbers -range 1 to 100.


It's required a data structure, in this case a list, to store the nth elements; that is define in line 8: List<int> nthElements = new List<int>();.


With this in mind, we got lines 11-13: here the expression Enumerable.Range(0, numbers.Count()/n) produces a range from 0 to 9; its purpose is allow the iteration of each nth element in the numbers list.


Now the code numbers.Skip(k*n).First() skips the k*n elements in numbers, and chooses the first element of the remaining elements generated by Skip(k*n).


Let's play an execution for this amazing LINQ code: 

7. Conclusions

An operation like pick an element from a collection is a common task; this recipe has showed us how to pick every nth element from a sequence by using the Skip() and First() methods.

The next recipe, the LINQ programmer will learn how to find the larger or smaller of several sequences at each index.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
Enumerable.Range Method (Int32, Int32) (System.Linq) (2016, July 7). Retrieved from: https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.110).aspx
Enumerable.Skip(TSource) Method (IEnumerable(TSource), Int32) (System.Linq) (2016, July 7). Retrieved from: https://msdn.microsoft.com/en-us/library/bb358985%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396


V

viernes, 17 de junio de 2016

LINQ Recipe No. 2-8: Mathematics and Statistics - How to Find a Cumulative Sum

Contents

1. Introduction
2. Keywords
3. Problem
4. Solution
5. Discussion
5.1 Cumulative sum
6. Practice: Cumulative Sum from 1 to 10 with LINQ
7. Conclusions
8. Literature & Links

1. Introduction

In this new LINQ recipe we are going to learn how to find the cumulative sum of a sequence of numbers. This will be accomplished, basically, using the generator function Range and the statistical function Sum. As we will see soon, this will allow us to compute partial sums of the growth percentage, year to year, in organization business process.

2. Keywords

  • Cumulative Sum
  • Generator function
  • LINQ
  • Partial sum
  • Statistical function

3. Problem

Find a way to find the cumulative of a sequence of numbers.

4. Solution

In the first place, it is required to have a sequence of values -this can be obtained from the Range generator function; and then with this new generated sequence, partial sums are computed by applying the Sum statistical function.

5. Discussion

5.1 Cumulative sum

According to "Cumulative Sum" (2016), a cumulative sum consists of a sequence of partial sums of a given succession. In formal mathematical notation, this concept is expressed as:
Sequence
then, to express the cumulative sum we compute partial sums as follows 
Cumulative sums
Each element of this sequence consists of a partial sum. A partial sum is basically the sum of each predecessor with the current element. The first element a does not have any predecessor element, so it is equals to itself.

A particular example can clarifies this concept better. Suppose we have the sequence of the values of the sales from January to June:

{500000, 900000, 600000, 750000, 880000, 820000}

now the cumulative sum is 

{500000, 500000 + 900000, 500000 + 900000 + 600000, 500000 + 900000 + 600000 + 750000, 500000 + 900000 + 600000 + 750000 + 880000, 500000 + 900000 + 600000 + 750000 + 880000 + 820000}

which is equals to 

{500000, 1400000, 2000000, 2750000, 3630000, 4450000}

6. Practice: Cumulative Sum from 1 to 10 with LINQ

This example shows us how to compute the cumulative sum using LINQ; in particular with these kinds of functions: 
  • Range (generator function), 
  • Sum (statistical function)
The range generated will represent the sequence: each element of this sequence will be summed up with its predecessor inside of a ForEach loop via the Sum function.

This is the LINQ code to perform this task: 

// Represents the sequence of cumulative sums:
Listint, int>> cumulativeSums =
new Listint, int>>();

// Sequence of numbers from 1 to 10:
var range = Enumerable.Range(1, 10);

// Compute the cumulative sum:
range.ToList().ForEach(
value => cumulativeSums.Add(
new KeyValuePair<int, int>(value, range.Take(value).Sum())
)
);

// Result:
cumulativeSums.Dump("Partial Sums at Each Level");

It's to time to execute these code statements in LINQPad: 
Cumulative sums of range 1-10
Figura 1. Cumulative sums of range 1-10.

7. Conclusions

We have understood how we can compute a cumulative sum -a sequence of partial sums- via LINQ standard query operators. LINQ expressivity allows us to elaborate complicated or extensive algorithms in a simpler way.

The coming up LINQ recipes are focused in recursive patterns: a pattern that can be expressed using a recurrence relation.

8. Literature & Links

Mukherjee, S (2014). Thinking in LINQ Harnessing the Power of Functional Programming in .NET Applications. United States: Apress.
Cumulative Sum -- from Wolfram MathWorld (2016, June 17). Retrieved from: http://mathworld.wolfram.com/CumulativeSum.html


V