tag:blogger.com,1999:blog-81977147423535166772014-10-05T00:41:19.971-07:00Aimless Technical Babble<center>Random insights that have come to me or most likely been shown to me from someone much wiser</center>Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.comBlogger8125tag:blogger.com,1999:blog-8197714742353516677.post-63550615487574452092011-08-16T08:59:00.000-07:002011-08-16T09:09:53.790-07:00Project Euler Problem #6<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />Time for Problem 6. (Don't worry. This one is fairly simple.)
<br /><blockquote>
<br /><code>The sum of the squares of the first ten natural numbers is,
<br />12 + 22 + ... + 102 = 385
<br />
<br />The square of the sum of the first ten natural numbers is,
<br />(1 + 2 + ... + 10)2 = 552 = 3025
<br />
<br />Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
<br />
<br />Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.</code>
<br /></blockquote>
<br />To me, this one screams brute force. In fact, I think it would be insulted if I executed any more brain power to develop a non-brute force method. So brute force it is.
<br />
<br />First we need to find the sum of the squares for 1-100. We can do this using Enumerables and lamda expressions and have it all in one handy dandy line of code:
<br /><div class="code">
<br /><pre class="brush: csharp"> var sumOfSquares = (long)Enumerable.Range(1, 100).Sum(i => Math.Pow(i, 2));</pre>
<br /></div>
<br />All this does is generate an enumeration of all numbers from 1 to 100 and sum each square.
<br />
<br />Now for the square of the sum:
<br /><div class="code">
<br /><pre class="brush: csharp"> var squareOfSum = (long)Math.Pow(Enumerable.Range(1, 100).Sum(), 2);</pre>
<br /></div>
<br />This is very similar to the previous, but we just grab the square of the sum of the number enumeration. That's it.
<br />
<br />Now we can combine it all and retrieve our final answer:
<br /><div class="code">
<br /><pre class="brush: csharp"> var sumOfSquares = (long)Enumerable.Range(1, 100).Sum(i => Math.Pow(i, 2));<br /> var squareOfSum = (long)Math.Pow(Enumerable.Range(1, 100).Sum(), 2);<br /> return squareOfSum - sumOfSquares;</pre>
<br /></div>
<br />And now we have our difference between the sum of squares and the square of the sum!
<br />Awesome.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-71145841385981682362011-08-11T12:49:00.000-07:002011-08-11T13:12:06.298-07:00Project Euler Problem #5<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />Ready or not, here comes problem five!
<br /><blockquote>
<br /><code>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
<br />
<br />What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</code>
<br /></blockquote>
<br />This one really doesn't require that much explanation. I suppose we could easily brute force this one also, but that just isn't my style. So I'll just go ahead and show the final return statement that gives us the answer:
<br /><div class="code">
<br /><pre class="brush: csharp"> return Enumerable.Range(1, 20).Aggregate(this.LeastCommonDivisor);</pre>
<br /></div>
<br />....Alright....that's it. Lets go home.
<br />
<br />No?
<br />
<br />Okay fine. Let me explain a bit. We are using the 'Aggregate' Extension here on our range of 1-20. The 'Aggregate' method will take our recursive method 'LeastCommonDivisor'.
<br />
<br />Here is that function:
<br /><div class="code">
<br /><pre class="brush: csharp"> private int LeastCommonDivisor(int i, int j)<br/> {<br/> return (i == 0) || (j == 0) ? 0 : (i / this.GreatestCommonDivisor(i, j)) * j;<br/> }</pre>
<br /></div>
<br />That function also makes reference to this function to recursively find the greatest common divisor:
<br /><div class="code">
<br /><pre class="brush: csharp"> private int GreatestCommonDivisor(int i, int j)<br/> {<br/> return (j == 0) ? i : this.GreatestCommonDivisor(j, i % j);<br/> }</pre>
<br /></div>
<br />Now our 'Aggregate' method will calculate the smallest positive number that is evenly divisible by all of the numbers from 1 to 20.
<br />
<br />This problem was not that enjoyable to me but oh well. I found some great references by <a href="http://basildoncoder.com/blog/2008/06/10/project-euler-problem-5/">Basildon Coder</a> and <a href="http://blog.functionalfun.net/2008/04/project-euler-problem-5.html">Functional Fun</a>. From these guys I was able to figure something out. Anyways here it is. Do with it what you will.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-66158567839439367112011-08-09T11:22:00.000-07:002011-08-09T22:21:02.278-07:00Project Euler Problem #4<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />Moving on along with these Project Euler problems, Problem 4 states this:
<br /><blockquote>
<br /><code>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
<br />
<br />Find the largest palindrome made from the product of two 3-digit numbers.</code>
<br /></blockquote>
<br />This just reeks of a brute force method. But that is fine. I don't think it will be that strenuous.
<br />
<br />First we need a function that determines if a computed number is a palindrome. This is what I came up with:
<br /><div class="code">
<br /><pre class="brush: csharp"> public bool IsPalindromic(string item)<br/> {<br/> return item.SequenceEqual(item.Reverse());<br/> }</pre>
<br /></div>
<br />Here we will take in a string representation of a number (or anything really) and use the handy 'SequenceEqual' and 'Reverse' extension methods. Now I actually read somewhere that the 'Reverse' method bogs down performance more than using any other method, but it wasn't enough to affect my performance so I kept it just because it is short and concise.
<br />
<br />Now we have to iterate through all the possibilities and check if the given product is a palindrome. There are two ways I can do this:
<br />
<br />Lambda:
<br /><div class="code">
<br /><pre class="brush: csharp"> return Enumerable.Range(100, 900)<br/> .Select(i => Enumerable.Range(i, 1000 - i)<br/> .Where(j => newTools.IsPalindromic((i * j).ToString()))<br/> .Select(j => i * j)<br/> .OrderBy(j => j)<br/> .LastOrDefault())<br/> .Max();</pre>
<br /></div>
<br />Or Linq:
<br /><div class="code">
<br /><pre class="brush: csharp"> return (from i in Enumerable.Range(100, 900)<br/> from j in Enumerable.Range(i, 1000 - i)<br/> let product = i * j<br/> where newTools.IsPalindromic(product.ToString())<br/> select product).Max();</pre>
<br /></div>
<br />Upon first glance the Linq option seems a lot cleaner and easier to read. And it might be. I guess I have no preference because both run just about as fast and return the correct answer, so it just depends on preference.
<br />
<br />There ya go. Easy as pie.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-53391934333119779912011-08-08T17:10:00.000-07:002011-08-09T22:20:48.528-07:00Dependency Injection For Dummies (aka Me)<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />For me, Dependency Injection used to be this wild crazy slick design pattern that I could probably never implement. Well, I was recently on a project for a client that ended up being a perfect situation for a Dependency Injection type implementation. The system was comprised of several assemblies that contained their own implementation. Of course that part is not foreign to me nor should it be to any mediocre developer. However, we ran into the issue of needing to add more of these assemblies in the future and the possibility of removing some. This all needed to happen without re-building/re-deploying the entire solution. Thus.....Dependency Injection. So I taught it to myself.
<br />
<br />In the project I was on, we ended up using an <a href="http://msdn.microsoft.com/en-us/library/ms173150.aspx">Abstract</a> class as our base instead of an Interface. Other than the preference of using Abstract classes, we found that there were some methods that could be common to several assemblies but not every one. So having an Abstract class made sense so that we could include some implementation in the class but also have the option to override it in the assemblies we needed it for.
<br />
<br />All this to say, I have decided to play around with Dependency Injection for my Project Euler obsession.
<br />
<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://3.bp.blogspot.com/-3wPbzh_dvas/TkCHtxp5RzI/AAAAAAAAAE4/dE5vMsRWqQM/s1600/di.jpg"><img style="display:block; margin:0px auto 10px; text-align:center;cursor:pointer; cursor:hand;width: 520px; height: 297px;" src="http://3.bp.blogspot.com/-3wPbzh_dvas/TkCHtxp5RzI/AAAAAAAAAE4/dE5vMsRWqQM/s320/di.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5638655953960781618" /></a>
<br />
<br />The way I set it up was to have each Problem as its own assembly with a Common assembly and then a User Interface. In the Common assembly, I have added an Abstract class (Problem) that has one method (Answer) that returns a long. Each Problem assembly will inherit from this base Problem class and use that Answer method to return all my answers. Which brings up another reason for Abstract Classes (or Interfaces); they act as contracts for any assembly that inherit from them. This insures that as long as they implement the right method; another assembly could be added and work without any issues. However, it does not stop me from returning the wrong answer because of my problematic logic :). Anyways, my main reason for using Dependency Injection was to basically limit the amount of assemblies I had to reference in my executing assembly. That would have been a mess.
<br />
<br />So how does it actually work? Alright, fine. I'll get to that now I guess. Here is a part of my App.Config file. This is where we will add a new assembly once created.
<br /><div class="code">
<br /><pre class="brush: xml">
<br /> <?xml version="1.0" encoding="utf-8" ?><br/> <configuration><br/> <configSections><br/> <sectionGroup name="spring"><br/> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/><br/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /><br/> </sectionGroup><br/> </configSections><br/> <spring><br/> <context><br/> <resource uri="config://spring/objects"/><br/> </context><br/> <objects xmlns="http://www.springframework.net"><br/> <description>All Individual Project Euler Problems</description><br/> <object name="Problem001" type="ProjectEuler.Problem001.Problem001, ProjectEuler.Problem001" /><br/> <object name="Problem002" type="ProjectEuler.Problem002.Problem002, ProjectEuler.Problem002" /><br/> <object name="Problem003" type="ProjectEuler.Problem003.Problem003, ProjectEuler.Problem003" /><br/> <object name="Problem004" type="ProjectEuler.Problem004.Problem004, ProjectEuler.Problem004" /><br/> <object name="Problem005" type="ProjectEuler.Problem005.Problem005, ProjectEuler.Problem005" /><br/> <object name="Problem006" type="ProjectEuler.Problem006.Problem006, ProjectEuler.Problem006" /><br/> <object name="Problem007" type="ProjectEuler.Problem007.Problem007, ProjectEuler.Problem007" /><br/> ............etc etc<br/> </objects><br/> </spring><br/> </configuration>
<br /></pre>
<br /></div>
<br />So this will be the only place we have the change something in order for a newly created assembly to work. (Granted that the DLL is in the executing bin folder.)
<br />
<br />Here is the code to place in my executing assembly to grab all the configurations in the configuration file:
<br /><div class="code">
<br /><pre class="brush: csharp"> using Spring.Context;</br></br> IApplicationContext context = ContextRegistry.GetContext();</pre>
<br /></div>
<br />Then I can use a for loop to grab the names of all the configured assemblies and use the 'GetObject' method to retrieve the object from the passed assembly name and cast it to the type of our Abstract class (Problem). Then viola, I call my 'Contracting Method' (Answer()) and I can get the answer to any assembly that is placed in the configuration file AND implements the Abstract class without changing my main code or re-compiling.
<br /><div class="code">
<br /><pre class="brush: csharp"> foreach(string problem in context.GetObjectDefinitionNames())</br> {<br/>  var answer = (Problem)context.GetObject(problem);<br/> Console.WriteLine(answer.Answer());<br/> }</pre>
<br /></div>
<br />I think that just about gives a BASIC walk-through of how I have learned to use Dependency Injection.
<br />
<br />Fun stuff.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-11493391467646093852011-08-08T13:13:00.000-07:002011-08-09T22:20:39.225-07:00Project Euler Problem #3<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />Time for Project Euler Problem 3.
<br /><blockquote>
<br /><code>The prime factors of 13195 are 5, 7, 13 and 29.
<br />
<br />What is the largest prime factor of the number 600851475143 ?</code>
<br /></blockquote>
<br />Ah. Prime numbers. This should be fun.
<br />
<br />Well first I think we need a fast and efficient way to generate prime numbers. There are many different to accomplish this, but I think making an iterator class to generate them will be best. It will be very similar to the generator we had for <a href="http://aimlesstechnicalbabble.blogspot.com/2011/08/project-euler-problem-2.html">Problem Two</a> to generate the Fibonacci sequence.
<br />
<br />Here is our generator class:
<br /><div class="code">
<br /><pre class="brush: csharp">
<br /> public class Primes : IEnumerable<long><br/> {<br/> private List<long> _primes;<br/><br/> public Primes()<br/> {<br/> _primes = new List<long>();<br/> _primes.Add(2);<br/> }<br/><br/> public IEnumerator<long> GetEnumerator()<br/> {<br/> Func<long, bool> IsPrime = n => _primes.TakeWhile(i => i <= (long)Math.Sqrt(n)).Count(i => (n % i).Equals(0)).Equals(0);<br/><br/> yield return 2;<br/> long next = 3;<br/><br/> while (true)<br/> {<br/> if (IsPrime(next))<br/> {<br/> _primes.Add(next);<br/> yield return next;<br/> }<br/> next += 2;<br/> }<br/> }<br/><br/> IEnumerator IEnumerable.GetEnumerator()<br/> {<br/> return GetEnumerator();<br/> }<br/> }
<br /></pre>
<br /></div>
<br />Now that we have our generator, all we have to do is generate primes up to the square root of 600851475143 and then take the largest factor. Easy enough.
<br /><div class="code">
<br /><pre class="brush: csharp"> long number = 600851475143;<br/> return new Primes().TakeWhile(i => i < (long)Math.Sqrt(number)).Where(i => (number % i).Equals(0)).Last();</pre>
<br /></div>Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-86111297581740165422011-08-07T15:02:00.000-07:002011-08-09T22:20:28.090-07:00Project Euler Problem #2<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />So these Project Euler problems have become quite addictive. I've actually already completed quite a few of them. However, this post will be devoted to problem number dos.
<br /><blockquote>
<br /><code>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
<br />
<br />1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
<br />
<br />By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</code>
<br /></blockquote>
<br />So this problem is asking us to find all the terms in the Fibonacci sequence that are even and under 4,000,000. Then we have to sum all of those terms.
<br />
<br />Alright, first we have to figure out the best way to generate our terms to use. The idea of the sequence is pretty straightforward. We start with two terms, 0 and 1, and then we can use an iterator block to return the second term to an enumerable object. Finally, we can set the second term to itself plus the first and set the first term equal to the new second minus the first.....confusing enough? Yea. Maybe this will help.
<br /><div class="code">
<br /><pre class="brush: csharp"> public IEnumerable<long> Fibonacci()<br/> {<br/> long a = 0;<br/> long b = 1;<br/><br/> while(true)<br/> {<br/> yield return b;<br/><br/> b = a + b;<br/> a = b - a;<br/> }<br/> }</pre>
<br /></div>
<br />So now we have a Fibonacci generator!
<br />
<br />So our final answer can be achieved by using a lambda expression with a 'TakeWhile' extension.
<br /><div class="code">
<br /><pre class="brush: csharp"> Tools newTools = new Tools();<br/> return newTools.Fibonacci().TakeWhile(i => i > 4000000).Where(i => newTools.IsEven(i)).Sum();</pre>
<br /></div>
<br />I have placed my Fibonacci Generator and the IsEven function in a "Tools" class. This will be my common assembly that will be used in each problems class. I've implemented <a href="http://msdn.microsoft.com/en-us/magazine/cc163739.aspx">Dependency Injection</a> on my solution just for the fun of it and will probably go over it in another post sometime. Who knows.
<br />
<br />Anyways, for good measure, here is my IsEven function:
<br /><div class="code">
<br /><pre class="brush: csharp"> public bool IsEven(long number)<br/> {<br/> return (number % 2 == 0);<br/> }</pre>
<br /></div>Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-21510072934671208102011-08-06T11:52:00.001-07:002011-08-09T22:16:00.494-07:00Project Euler Problem #1<a style="display:none" href="http://www.codeproject.com/script/Articles/BlogFeedList.aspx?amid=8053875" rel="tag">CodeProject</a>
<br />Alright, here we go on Project Euler. Time for the first problem:
<br /><blockquote>
<br /><code>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.
<br />
<br />Find the sum of all the multiples of 3 or 5 below 1000.</code>
<br /></blockquote>
<br />That doesn't sound quite that hard. Right? The first problem couldn't possibly be hard.
<br />
<br />Well let's break it down. All the numbers that are multiples of 3 or 5 under 10 are 3, 5, 6 and 9. Or in other words, 3, 5, 6 and 9 are the only numbers (under 10) that are divisible by 3 or 5 and leave no remainder behind.
<br />
<br />So now we have to find all the numbers under 1000 that satisfy the same requirement. And then sum those numbers.
<br />
<br />At first thought I suppose it would be easy enough to create a loop that goes through each possibility and adds the number to a list if it passes the divisible test.
<br />
<br />Something like this:
<br />
<br /><div class="code">
<br /><pre class="brush: csharp"> List<int> multiples = new List<int>();<br/><br/> for (int i = 1; i < 1000; i++)<br/> {<br/> if ((i % 3 == 0) || (i % 5 == 0))<br/> {<br/> multiples.Add(i);<br/> }<br/> }<br/><br/> return multiples.Sum();</pre>
<br /></div>
<br />Simple enough right? Well yes and for this simple type of problem, it won't really have any affect on performance. However, I wanted the least amount of lines as possible. I had recently discovered the wonderful world of lambda expressions and I feel that I should use them as often as I can. (for better or for worse)
<br />
<br />So here is my solution:
<br /><div class="code">
<br /><pre class="brush: csharp"> return Enumerable.Range(1, 999).Where(i => (i % 3).Equals(0) || (i % 5).Equals(0)).Sum();</pre>
<br /></div>
<br />Ah. Enumerables. By using the 'Range' extension I can retrieve an enumerable list of ints to select from. The 'Where' extension method will ensure that I only retrieve the numbers that are multiples of 3 or 5. And finally, the 'Sum' extension will return the sum of all the numbers left.
<br />
<br />Or if we want to get really fancy, we could create a lambda function delegate to make things a bit more readable:
<br />
<br /><div class="code">
<br /><pre class="brush: csharp"> Func<int, int, bool> IsMultiple = (int i, int j) => (i % j).Equals(0);<br/> return Enumerable.Range(1, 999).Where(i => IsMultiple(i, 3) || IsMultiple(i, 5)).Sum();</pre>
<br /></div>
<br />However, the previous solution will do in this case.
<br />
<br />Simple and concise. KISS principle in action.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0tag:blogger.com,1999:blog-8197714742353516677.post-40832814269178847232011-08-06T10:18:00.000-07:002011-08-07T19:47:13.617-07:00Project EulerI recently finished up my summer internship with <a href="http://www.askcts.com">CTS</a> and while I wait for my last semester to start, I felt that I should find something to keep my mind sharp and possibly improve some programming skills.<br /><br />This is how I came across <a href="http://projecteuler.net">Project Euler</a>. This site consists of many mathematical type problems that require programming skills to solve. Now I never had a love for math, in fact quite the opposite. However, this looked promising to not only sharpen some problem solving skills but maybe refresh what "math" knowledge I have rattling around in my brain.<br /><br />Therefore, I am going to post some of my solutions for these problems whenever I can. I am going to solve these problems using C# and the .NET 4 Framework.<br /><br />Should be fun.Jaredhttp://www.blogger.com/profile/08882790106781034357noreply@blogger.com0