About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).
Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Friday, March 15, 2013

Just for kicks: Project Euler Problem #1

Just wanted to try a variety of methods to a solution. I wanted to do a variety of parallel, plinq, and straight forward logic test. I also wanted to implement a extension method and use func<> for better refactoring. As a test, I considered doing Euler's #1:
http://projecteuler.net/problem=1


Here are the several methods I created:
Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7.  
  8. namespace ProjectEuler
  9. {
  10.     /*
  11.      *   Q: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
  12.      *      Find the sum of all the multiples of 3 or 5 below 1000.
  13.      *
  14.      *   A: 233168
  15.      *   
  16.      *   Results:
  17.                     Method 1 Avg Time:  0.000007768
  18.                     Method 2a Avg Time: 0.000040169
  19.                     Method 2b Avg Time: 0.000029314
  20.                     Method 2c Avg Time: 0.000347431
  21.                     Method 2d Avg Time: 0.000175544
  22.                     Method 3a Avg Time: 0.00017445
  23.                     Method 3b Avg Time: 0.000144669
  24.                     Method 3c Avg Time: 0.002392947
  25.                     Method 3d Avg Time: 0.001309331
  26.      *   
  27.      */
  28.     class Problem1
  29.     {
  30.         int[] items = Enumerable.Range(1, 999).ToArray();
  31.         ReaderWriterLockSlim rw = new ReaderWriterLockSlim();
  32.         int sum = 0;
  33.  
  34.         //KISS Logic
  35.         public int RunMethod1()
  36.         {
  37.             sum = 0;
  38.  
  39.             foreach(int s in items)
  40.             {
  41.                 if (s % 3 == 0 || s % 5 == 0)
  42.                 {
  43.                     sum += s;
  44.                 }
  45.             };
  46.  
  47.             return sum;
  48.         }
  49.  
  50.         //Lazy Method
  51.         public int RunMethod2a()
  52.         {
  53.             return items.Where(n => n % 3 == 0 || n % 5 == 0).Sum();
  54.         }
  55.  
  56.         //Lazy Method on the fly
  57.         public int RunMethod2b()
  58.         {
  59.             return Enumerable.Range(1, 999).Where(n => n % 3 == 0 || n % 5 == 0).Sum();
  60.         }
  61.  
  62.         //Parallel Lazy Method
  63.         public int RunMethod2c()
  64.         {
  65.             return items.AsParallel().Where(n => n % 3 == 0 || n % 5 == 0).Sum();
  66.         }
  67.  
  68.         //Parallel Lazy Method on the fly
  69.         public int RunMethod2d()
  70.         {
  71.             return Enumerable.Range(1, 999).AsParallel().Where(n => n % 3 == 0 || n % 5 == 0).Sum();
  72.         }
  73.  
  74.         //Basic Parallel Method
  75.         public int RunMethod3a()
  76.         {
  77.             List<int> multOf3Or5 = new List<int>();
  78.  
  79.             Parallel.ForEach(items, s =>
  80.                 {
  81.                     if (s % 3 == 0 || s % 5 == 0)
  82.                     {
  83.                         lock (multOf3Or5)
  84.                         {
  85.                             multOf3Or5.Add(s);
  86.                         }
  87.                     }
  88.                 }
  89.             );
  90.  
  91.             return multOf3Or5.Sum();
  92.         }
  93.  
  94.         //Parallel it, but slice the work up
  95.         public int RunMethod3b()
  96.         {
  97.             List<int> multOf3Or5 = new List<int>();
  98.  
  99.             Parallel.ForEach(items.Slice(100), s =>
  100.             {
  101.                 foreach (int item in s)
  102.                 {
  103.                     if (item % 3 == 0 || item % 5 == 0)
  104.                     {
  105.                         lock (multOf3Or5)
  106.                         {
  107.                             multOf3Or5.Add(item);
  108.                         }
  109.                     }
  110.                 }
  111.             });
  112.  
  113.             return multOf3Or5.Sum();
  114.         }
  115.  
  116.  
  117.         //Basic Parallel Method just sum it
  118.         public int RunMethod3c()
  119.         {
  120.             sum = 0;
  121.  
  122.             Parallel.ForEach(items, s =>
  123.             {
  124.                 if (s % 3 == 0 || s % 5 == 0)
  125.                 {
  126.                     rw.EnterWriteLock();
  127.                     sum += s;
  128.                     rw.ExitWriteLock();
  129.                 }
  130.             });
  131.  
  132.             return sum;
  133.         }
  134.  
  135.         //Basic Parallel Method just slice & sum it
  136.         public int RunMethod3d()
  137.         {
  138.             sum = 0;
  139.             
  140.             Parallel.ForEach(items.Slice(100), s =>
  141.             {
  142.                 foreach (int item in s)
  143.                 {
  144.                     if (item % 3 == 0 || item % 5 == 0)
  145.                     {
  146.                         rw.EnterWriteLock();
  147.                         sum += item;
  148.                         rw.ExitWriteLock();
  149.                     }
  150.                 }
  151.             });
  152.  
  153.             return sum;
  154.         }
  155.     }
  156. }

Method 1: is the straight forward logic I would have used, and seems to be the quickest.
Method 2s: is probably something I would use as well, and to clean code up.
Method 3s: using Parallel programming, doesn't always speed things up. Depends on how much work needs to be done. I used an Extension method called Slice which expands the use of enumerable. I mainly got the idea to do this after reading about extention methods from http://www.blackrabbitcoder.net/archive/2013/03/08/c.net-little-wonders-extension-methods-demystified.aspx

For the Slice Extension, I used this:
Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ProjectEuler
  7. {
  8.     public static class EnumerableExtensions
  9.     {
  10.         //Source and Inspiration: http://www.blackrabbitcoder.net/archive/2013/03/08/c.net-little-wonders-extension-methods-demystified.aspx
  11.  
  12.         public static IEnumerable<IEnumerable<T>> Slice<T>(this IEnumerable<T> source, int size)
  13.         {
  14.             // can't slice null sequence
  15.             if (source == null) throw new ArgumentNullException("source");
  16.             if (size < 1) throw new ArgumentOutOfRangeException("size", "The size must be positive.");
  17.  
  18.             // force into a list to take advantage of direct indexing. Could also force into an
  19.             // array, use LINQ grouping, do a Skip()/Take(), etc...
  20.             var sourceList = source.ToList();
  21.             int current = 0;
  22.      
  23.             // while there are still items to "slice" off, keep going
  24.             while (current < sourceList.Count)
  25.             {
  26.                 // return a sub-slice using an iterator for deferred execution
  27.                 yield return sourceList.GetRange(current, Math.Min(size, sourceList.Count - current));
  28.                 current += size;
  29.             }
  30.         }
  31.     }
  32. }

The Main program. I hate repeating myself, so after some refactoring I came up with this to use delegates.
Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics;
  6.  
  7. namespace ProjectEuler
  8. {
  9.     class Program
  10.     {
  11.         public static Stopwatch sw = new Stopwatch();
  12.         public delegate int fPointer();
  13.  
  14.         static void Main(string[] args)
  15.         {
  16.             //Initialize Problem(s)
  17.             Problem1 p1 = new Problem1();
  18.  
  19.             Func<fPointer,int, double> timeIt = (d,runCount) =>
  20.             {
  21.                 List<double> times = new List<double>();
  22.  
  23.                 for (int i = 0; i < runCount; i++)
  24.                 {
  25.                     sw.Reset();
  26.                     sw.Start();
  27.                     d();
  28.                     sw.Stop();
  29.                     times.Add(sw.Elapsed.TotalSeconds);
  30.                 }
  31.                 return times.Average();
  32.             };
  33.  
  34.             //Get Times of Running Methods
  35.             Console.WriteLine("Method 1 Avg Time: " + timeIt(p1.RunMethod1,100));
  36.             Console.WriteLine("Method 2a Avg Time: " + timeIt(p1.RunMethod2a, 100));
  37.             Console.WriteLine("Method 2b Avg Time: " + timeIt(p1.RunMethod2b, 100));
  38.             Console.WriteLine("Method 2c Avg Time: " + timeIt(p1.RunMethod2c, 100));
  39.             Console.WriteLine("Method 2d Avg Time: " + timeIt(p1.RunMethod2d, 100));
  40.             Console.WriteLine("Method 3a Avg Time: " + timeIt(p1.RunMethod3a, 100));
  41.             Console.WriteLine("Method 3b Avg Time: " + timeIt(p1.RunMethod3b, 100));
  42.             Console.WriteLine("Method 3c Avg Time: " + timeIt(p1.RunMethod3c, 100));
  43.             Console.WriteLine("Method 3d Avg Time: " + timeIt(p1.RunMethod3d, 100));
  44.  
  45.             Console.ReadKey();
  46.         }
  47.     }
  48. }

Monday, February 04, 2013

A couple of Linq to Sql Query Examples


Just a quick reference of a couple basic query conversions for Linq to SQL




Code Snippet
  1. //inner join
  2.             //SELECT [t0].[CountyName]
  3.             //FROM [dbo].[County] AS [t0]
  4.             //INNER JOIN [dbo].[State] AS [t1] ON [t0].[StateID] = [t1].[StateID]
  5.             //WHERE LOWER([t1].[StateName]) = @p0
  6.             var counties =  from c in db.Counties
  7.                             join st in db.States on c.StateID equals st.StateID
  8.                             where st.StateName.ToLower().Equals("florida")
  9.                             select c.CountyName;
  10.  
  11.  
  12.             //left join -- use DefaultIfEmpty and new object
  13.             //SELECT [t0].[CountyName],
  14.             //(CASE WHEN [t2].[test] IS NULL THEN CONVERT(NVarChar(50),@p0)
  15.             //      ELSE CONVERT(NVarChar(50),[t2].[StateName])
  16.             //      END) AS [StateName]
  17.             //FROM [dbo].[County] AS [t0]
  18.             //LEFT OUTER JOIN
  19.             //(
  20.             //      SELECT 1 AS [test], [t1].[StateID], [t1].[StateName]
  21.             //      FROM [dbo].[State] AS [t1]
  22.             //) AS [t2] ON [t0].[StateID] = [t2].[StateID]
  23.             var counties2 = from c in db.Counties
  24.                             join st in db.States on c.StateID equals st.StateID
  25.                             into stateCounties
  26.                             from co in stateCounties.DefaultIfEmpty()
  27.                             select new { CountyName = c.CountyName, StateName = (co == null)? "": co.StateName };
  28.  
  29.  
  30.             //Same table query
  31.             //SELECT [t0].[CountyName]
  32.             //FROM [dbo].[County] AS [t0],
  33.             //     [dbo].[County] AS [t1]
  34.             //WHERE ([t0].[CountyName] = [t1].[CountyName]) AND ([t0].[CountyID] <> [t1].[CountyID])
  35.             var counties3 = from c1 in db.Counties
  36.                             from c2 in db.Counties
  37.                             where c1.CountyName == c2.CountyName && c1.CountyID != c2.CountyID
  38.                             select new
  39.                             {
  40.                                 CountyName = c1.CountyName,
  41.                             };
  42.  
  43.  
  44.  
  45.  
  46.             var counties4 = (from c1 in db.Counties
  47.                             from c2 in db.Counties
  48.                             where c1.CountyName == c2.CountyName && c1.CountyID != c2.CountyID
  49.                             group c1 by c1.CountyName into dups
  50.                             select new
  51.                             {
  52.                                 CountyName = dups.Key,
  53.                                 Count = dups.Count()
  54.                             }
  55.                             ).OrderBy(n => n.CountyName);

Some resources I found useful:
http://codesamplez.com/database/linq-to-sql-join-tutorials
http://weblogs.asp.net/rajbk/archive/2010/03/12/joins-in-linq-to-sql.aspx

http://msdn.microsoft.com/en-us/library/bb386913.aspx
   More specifically to joins:
   http://msdn.microsoft.com/en-us/library/bb399397.aspx

Thursday, January 08, 2009

Permutations. The nth permutation from an ordered set of permutations.

So, I was doing Euler 24 from Project Euler. I thought of an interesting way of find the nth permutation from a set. Here is my solution:

       
Code Snippet
  1. /*A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the
  2.         digits 1, 2, 3 and 4.
  3.         * If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
  4.         012   021   102   120   201   210
  5.         What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
  6.         */
  7.         //.01 seconds
  8.         static void Main(string[] args)
  9.         {
  10.             Stopwatch sw = new Stopwatch();
  11.             sw.Start();
  12.             int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  13.             char[] letters = new char[] {'a','b','c','d','e','f','g','h','i','j'};
  14.             Console.WriteLine(findPermutationAtElement<int>(numbers, 999999));
  15.             Console.WriteLine(findPermutationAtElement<char>(letters, 999999));
  16.             sw.Stop();
  17.             Console.WriteLine(sw.Elapsed);
  18.             Console.ReadLine();
  19.         }
  20.         private static string findPermutationAtElement<T>(T[] numbers, int p)
  21.         {
  22.             string answer = "";
  23.             ulong totalPerms;
  24.             int position;
  25.             ulong section;
  26.             T[] temp;
  27.             int length = numbers.Length;
  28.             //make sure array is ordered
  29.             numbers = numbers.OrderBy(n => n).ToArray();
  30.             for (int i = 0; i < length; i++)
  31.             {
  32.                 //find number of permutations left
  33.                 totalPerms = factorial(numbers.Length);
  34.                 //find what section number will fall into
  35.                 section = totalPerms / (ulong)numbers.Length;
  36.                 //find whole number index
  37.                 position = p / (int)section;
  38.                 //change p to reflect sub array position
  39.                 p = p % (int)section;
  40.                 //put value at the end
  41.                 answer = answer.Insert(answer.Length, numbers.ElementAt(position).ToString());
  42.                 //remove element from array
  43.                 temp = new T[numbers.Length - 1];
  44.                 for (int j = 0; j < numbers.Length; j++)
  45.                 {
  46.                     if (j == position)
  47.                     {
  48.                     }
  49.                     else if (j > position)
  50.                     {
  51.                         temp[j - 1] = numbers[j];
  52.                     }
  53.                     else
  54.                     {
  55.                         temp[j] = numbers[j];
  56.                     }
  57.                 }
  58.                 numbers = temp;
  59.             }
  60.             return answer;
  61.         }
  62.         private static ulong factorial(int p)
  63.         {
  64.             if (p == 0)
  65.             {
  66.                 return 1;
  67.             }
  68.             return (ulong)p * factorial(p - 1);
  69.         }

Wednesday, January 23, 2008

LINQ's "Outer Variables in a Loop"

Started using LINQPad and going through the "C# 3.0 in a Nutshell" tutorial that came with the program.

Then I ran the following script from "Chapter 8 - LINQ Queries/Deferred Execution/Outer Variables in a Loop" :

IEnumerable<char> query = "Not what you might expect";

 

query = query.Where (c => c != 'a');

query = query.Where (c => c != 'e');

query = query.Where (c => c != 'i');

query = query.Where (c => c != 'o');

query = query.Where (c => c != 'u');

 

new string (query.ToArray()).Dump ("All vowels are stripped, as you'd expect.");

 

query = "Not what you might expect";

 

foreach (char vowel in "aeiou")

{

    query = query.Where (c => c != vowel);

}

 

new string (query.ToArray()).Dump ("Notice that only the 'u' is stripped!");

 

with the following results:

▪ All vowels are stripped, as you'd expect.

Nt wht y mght xpct

▪ Notice that only the 'u' is stripped!

Not what yo might expect

 

 

Very confusing hmmm..., here is the solution (add a temp variable):

foreach (char vowel in "aeiou")

{

   char temp = vowel;

   query = query.Where (c => c != temp);

}

 

Reason:

"The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop." -- C# 3.0 IN A NUTSHELL http://www.albahari.com/nutshell/predicatebuilder.html

 

I would like a more detail explanation of this.

I'm guessing that the variable vowel goes through some sort of reset each time the foreach loop is ran, so in the end you will be actually checking

query = query.Where (c => c != 'u');

query = query.Where (c => c != 'u');

query = query.Where (c => c != 'u');

query = query.Where (c => c != 'u');

query = query.Where (c => c != 'u');

 

instead of

query = query.Where (c => c != 'a');

query = query.Where (c => c != 'e');

query = query.Where (c => c != 'i');

query = query.Where (c => c != 'o');

query = query.Where (c => c != 'u');

Friday, August 17, 2007

LINQ and AI?

Well, LINQ is something new to both VB and C# in Visual Studio 8 that allows you to query the data. The data can be XML, ADO.NET, DataSet, or objects. An example of the LINQ format:

var locals = (from c in customers
where c.ZipCode == 91822
select new { FullName = c.FirstName + “ “ +
c.LastName, HomeAddress = c.Address})
.Count();

What I find really interesting about the possibility of using LINQ, is the idea that the program can look at itself in an evaluation. If you add some artificial intelligence, this idea can be a great help in developing programs that can prove themselves correct in logic. I even think, that this concept can be used, with lots of time and planning, to develop a program that can write other programs given a set of parameters and acceptable outcomes.

The concept of using a database like language in a structure language is a very nice concept. If LINQ could be used to select all number of the type Int32 to represent integer numbers, would be something fun to play with. On this subject I might be a little too much in the dream world at the momement, but I do look forward to the possibilities.

Some sources on LINQ:

http://msdn.microsoft.com/msdnmag/issues/07/06/CSharp30/
http://blogs.msdn.com/charlie/archive/2007/07/26/visual-studio-2008-beta-2-released.aspx

Some info on Lambda Calculus:

http://en.wikipedia.org/wiki/Typed_lambda_calculus