2010: The year we make contact RSS 2.0
# Sunday, July 26, 2009

Find nearest object query with LINQ

While LINQ simplifies your DAL in myriad ways, this seemingly simple query made me stop and think about how to properly explain this to the query engine

Problem: Given an input of a current location (latitude and longitude) find all objects in the database within a specified radius

Disclaimer: This is using a bounding box hack rather than an accurate radius forumula, use at your own risk as there is some loss of precision.

     /// Find all courts within a specified radius (in miles) to a point (latitude & longitude)
     /// <param name="latitude">degrees(decimal)</param>
     /// <param name="longitude">degrees(decimal)</param>
     /// <param name="radius">miles</param>
     /// <returns></returns>
     public IQueryable<Court> FindNearbyCourts(decimal latitude, decimal longitude, decimal radius);

The first order of business is to convert miles to degrees of latitude and longitude, respectively.

Latitude:     Factor out Equatorial bulge, and a degree of latitude is simply 69.04 statute miles.
Longitude:     On the other hand, longitude varies in length depending on your current latitude. For this example, I am assuming 30°N. Thus, one degree of longitude is 59.96 statute miles.
     decimal radiusLatitude = radius / 69.04;
     decimal radiusLongitude = radius / 59.96;

Once we have these conversions in place, we are ready to build our LINQ query:

     IQueryable<Court> nearbyCourts = from court in _db.Courts 
where
(Math.Abs(court.latitude - latitude) < radiusLatitude)
where (Math.Abs(court.longitude - longitude) < radiusLongitude)
select court;

Return the IQueryable object nearbyCourts you just generated and you're all set.

Sunday, July 26, 2009 11:34:18 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
Bookmark, Tweet, or Share
# Sunday, March 01, 2009

Google provides a Charting API with a host of useful charts. I spent a few minutes playing around with the map chart section to create a color-coded map of the states I have visited in the USA.

chart

The Venn Diagram was an interesting option that I had not expected, but good stuff.

chart

If you are building a dashboard, the Google-o-meter might come in handy

chart
Sunday, March 01, 2009 1:32:00 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
# Sunday, February 22, 2009

I find myself spending quite a bit of my spare time on Stackoverflow in recent weeks, and decided I wanted to display my current rep on my blog.  A few days ago I built a dynamically generated (and cached for 2 hours for traffic's sake) user ranking report, since my request for this on Uservoice was not approved.

HtmlAgilityPack has been my weapon of choice in recent days.  It was a good fit for this project and the end result looks like this:

stack overflow badge

And in case you might ask "Show me the code!" here you are.  Feel free to use it for your own project if you like.

<%@ WebHandler Language="C#" Class="Badge" %>

using System;
using System.Web;

public class Badge : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) 
    {
        string includeLogo = !string.IsNullOrEmpty(context.Request.QueryString["useLogo"]) ? 
context.Request.QueryString["useLogo"] : string.Empty; string userId = !string.IsNullOrEmpty(context.Request.QueryString["userid"]) ?
context.Request.QueryString["userid"] : "1551"; string jsMode = !string.IsNullOrEmpty(context.Request.QueryString["jsMode"]) ?
context.Request.QueryString["jsMode"] : string.Empty; PageRetriever pr = new PageRetriever("http://stackoverflow.com/users/" + userId + "/"); pr.GetPage(); User userBadges = pr.ExtractBadge(); if (!string.IsNullOrEmpty(jsMode)) { context.Response.ContentType = "text/javascript"; context.Response.Write("document.getElementById('stackoverflowRep').innerHTML = '"); } else { context.Response.ContentType = "text/html"; } if (!string.IsNullOrEmpty(includeLogo)) { context.Response.Write("<div style=\"height:40px\"><div style=\"float:left\"></div><div style=\"float:left;\">");
context.Response.Write(<img src=\"http://www.chrisballance.com/so/resources/stackoverflow-logo-250.png\" />");
} context.Response.Write(userBadges.Rep); if (!string.IsNullOrEmpty(includeLogo)) { context.Response.Write("<br /><a href=\"http://stackoverflow.com/users/"); context.Response.Write(userId); context.Response.Write("\">"); context.Response.Write(userBadges.Username); context.Response.Write("</a></div></div></div>"); } if (!string.IsNullOrEmpty(jsMode)) { context.Response.Write("';\n"); } } public bool IsReusable { get { return false; } } }

 

Sunday, February 22, 2009 11:10:06 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
# Tuesday, February 17, 2009

Since I could not find a chart of some sort showing current rankings on StackOverflow.com, I decided to roll my own.  The link that follows points to a static cached version of the page that will only update manually for now.  Enjoy, and feel free to give your feedback or suggestions for improvements.

Current StackOverflow.com Rankings

Stackoverflow.com Rankings
Tuesday, February 17, 2009 1:16:09 AM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
Bookmark, Tweet, or Share
# Tuesday, February 10, 2009

F# has 'easy button' for finding large primes!  29 lines of code!  Thanks to Chris Smith and his 'completely unique view' on the Sieve of Eratosthenes

#light 

open System.Collections.Generic 
open System 

let findPrimes = 
    seq { 
        yield 2 //2 is a known prime

        let knownComposites = new HashSet<int>() 
        
        //Visit each odd
        for i in 3 .. 2 .. int 1E6 do 
            
            // Check known composites, if not present, it is prime.
            let found = knownComposites.Contains(i) 
            if not found then 
                yield i 

            // Add all multiples of i to our sieve, starting 
            // at i and irecementing by i. 
            do for j in i .. i .. int 1E6 do 
                   knownComposites.Add(j) |> ignore 
    } 
    
printfn "Here are the first 10001 primes:" 
Seq.iter (fun p -> printf "\t%d" p) (Seq.take 10001 findPrimes) 

Console.ReadKey(true)
Tuesday, February 10, 2009 12:15:23 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
# Monday, February 09, 2009

Euler #6 is very straightforward. I was concerned about needing to work with numbers > 2^32, but this was not a factor. I initially set my bound to < max instead of <= max which threw my results off my a small margin (1-99 instead of 1-100). Runtime is < 1 ms, only ~2400 ticks.

using System;
using System.Diagnostics;

namespace Euler6
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            long result = SumDifference(1, 100);
            sw.Stop();
            Console.WriteLine("Runtime was " + sw.ElapsedMilliseconds + " ms");
            Console.WriteLine("Runtime was " + sw.ElapsedTicks +" ticks");
            Console.WriteLine("Sum difference is: " + result);
            Console.ReadLine();

        }

        static long SumDifference(int begin, int end)
        {
            return SquareOfSums(begin, end) - SumOfSquares(begin, end);
        }

        static long SumOfSquares(int begin, int end)
        {
            long returnValue = 0;
            for (int i = begin; i <= end; i++)
            {
                returnValue += Convert.ToInt64(Math.Pow(i,2));
            }
            return returnValue;
        }

        static long SquareOfSums(int begin, int end)
        {
            long returnValue = 0;
            for (int i = begin; i <= end; i++)
            {
                returnValue += i;
            }
            return Convert.ToInt64(Math.Pow(returnValue, 2));
        }
    }
}
Monday, February 09, 2009 11:01:49 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share

This one was elusively easy since I went with a simple brute-force approach. Execution averages 1 second.
using System;
using System.Diagnostics;

namespace Euler5
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            int lcm = FindLeastCommonMultiple();
            sw.Stop();
            Console.WriteLine("Runtime was " + sw.ElapsedMilliseconds + " ms");
            Console.WriteLine("Runtime was " + sw.ElapsedTicks + " ticks");
            Console.WriteLine("LCM is " + lcm);
            Console.ReadLine();
        }

        private static int FindLeastCommonMultiple()
        {
            for (int i = 2520; i < int.MaxValue; i += 20)
            {
                if (IsDivisibleByRange(i, 1, 20))
                    return i;
            }
            return -1;
        }

        static long SmallestNumber()
        {
            return factorial(20);
        }

        static long factorial(long n)
        {
            long returnValue = 1;
            for (int i = 1; i < n; i++)
            {
                returnValue *= i;
            }
            return returnValue;
        }

        static bool IsDivisibleByRange(int num, int begin, int end)
        {
            for (int i = begin; i <= end; i++)
            {
                if ((num % i) != 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
}
Monday, February 09, 2009 10:44:54 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share

There is certainly a more efficient algorithm solve Euler #4, but here is my solution.  Runtime averages around 500ms.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Diagnostics;

namespace Euler4
{
    class Program
    {
        static void Main(string[] args)
        {
            long maxPal = 0;
            long iMax = 0;
            long jMax = 0;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 100; i <= 999; i++)
            {
                for (int j = 100; j <= 999; j++)
                {
                    long curPal = (long)(i * j);
                    if (CheckPallindrome(curPal))
                    {
                        if (curPal > maxPal)
                        {
                            maxPal = curPal;
                            iMax = i;
                            jMax = j;
                        }
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("Runtime was " + sw.ElapsedMilliseconds + " ms");
            Console.WriteLine("Runtime was " + sw.ElapsedTicks + " ticks ");
            Console.WriteLine(iMax + " x " + jMax + " = " + maxPal);
            Console.ReadLine();
            
        }

        private static bool CheckPallindrome(long input)
        {
            PallindromeChecker pc = new PallindromeChecker();
            pc.Pal = input;
            return pc.IsPallindrome();
        }
    }

    class PallindromeChecker
    {
        private long _pal;
        private string forward, reverse;

        public long Pal
        {
            get
            {
                return _pal;
            }
            set
            {
                _pal = value;
            }
        }


        public bool IsPallindrome()
        {
            GetReversedLong();
            if (forward == reverse)
                return true;

            return false;
        }

        private void GetReversedLong()
        {
            forward = Convert.ToString(_pal);
            StringBuilder temp2 = new StringBuilder();

            char[] arr = new char[forward.Length - 1];
            arr = forward.ToCharArray();
            for (int i = forward.Length - 1; i >= 0; i--)
            {
                temp2.Append(arr[i]);
            }
            reverse = temp2.ToString();
        }
    }
}
Monday, February 09, 2009 10:26:20 PM (Eastern Standard Time, UTC-05:00)  #    Comments [1] -
Bookmark, Tweet, or Share
# Wednesday, January 21, 2009

  In an effort to improve my algorithm design I have been working through some of the problems in the Euler Project and have found some of them to be quite intriguing.

Q: What is the largest prime factor of the number 600851475143 ?

I had the following issues to ponder:

  • How to store and manipulate a 40-bit unsigned integer?
  • To utilize recursion or not?
  • Will the algorithm run in less than a minute?
    • If not, how do I make it more efficient?

The end result was simpler and much more performant than I had expected.  The 40-bit input fit into a long just fine.  Recursion was not necessary, and average runtimes are in the single digit millisecond range.  There was even an opportunity to use some very basic LINQ to retrieve the largest factor from the List

Here is the C# code:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

namespace Euler3
{
    class PrimeFactorization
    {
        const long ToFactor = 600851475143;
        public static List<long> theFactors = new List<long>();

        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();

            Console.WriteLine("Highest prime factor of (" + ToFactor + ") is " + HighestPrimeFactor(ToFactor));
            sw.Stop();
            Console.WriteLine("Factorization algorithm runtime was: " + sw.ElapsedTicks + " ticks or " + sw.ElapsedMilliseconds + "ms");
            
            Console.ReadLine();
        }

        private static long HighestPrimeFactor(long input)
        {
            bool searching = true;
            long highestFactor = 0;
            while (searching)
            {
                long factor = IsPrime(input);
                if (factor != -1)
                {
                    theFactors.Add(factor);
                    input = input / factor; 
                }
                if (factor == -1)
                {
                    theFactors.Add(input);
                    highestFactor = theFactors.Max();
                    searching = false;
                }
            }
            return highestFactor;
        }

        private static long IsPrime(long input)
        {
            if ((input % 2) == 0)
            {
                return 2;
            }
            else if ((input == 1))
            {
                return 1;
            }
            else
            {
                long threshold = (Convert.ToInt64(Math.Sqrt(input)));
                long tryDivide = 3;
                while (tryDivide < threshold)
                {
                    if ((input % tryDivide) == 0)
                    {
                        Console.WriteLine("Found a factor: " + tryDivide);
                        return tryDivide;
                    }
                    tryDivide += 2;
                }
                Console.WriteLine("Found a factor: " + input);
                return -1;
            }
        }
    }
}
Output:
-Surely a blog entry title such as this earns me some sort of special place in Geek Hell.
Wednesday, January 21, 2009 10:42:21 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Bookmark, Tweet, or Share
# Monday, April 07, 2008


Monday, April 07, 2008 8:11:57 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
Bookmark, Tweet, or Share
Stackoverflow.com Rep
Flickr stream
Archive
<March 2010>
SunMonTueWedThuFriSat
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Chris Ballance
Sign In
Statistics
Total Posts: 41
This Year: 6
This Month: 0
This Week: 0
Comments: 9
All Content © 2010, Chris Ballance

Valid XHTML 1.0 Transitional