Euler Problem 205


Euler Problem 205:

Ako generiramo sve slučajeve koje Peter može dobiti bacanjem 9 piramida, te sve slučajeve koje Colin može dobiti bacanjem svoje kocke, zadatak se svodi da se kompariraji dobijeni rezultati na način da se napravi omjer slučajeva pobjede Petera sa ukupnim omjerom. Implementacija rješenja napravljena je sa LINQ, koja u mnogome pojednostavljiva rješenje. Prva dva upita se moraju keširati u listu da bi se algoritam ubrzao, koji u ovoj fazi se izvršava za oko 9 sec.  Još ako se na zadnjem upitu doda AsParallel(), onda se izvršavanje koda završava za oko 3 sekunde na Quad Core mašini.

namespace EulerProblem205
{
    class Program
    {
        static void Main(string[] args)
        {
            var peter = (from p1 in Enumerable.Range(1, 4)
                         from p2 in Enumerable.Range(1, 4)
                         from p3 in Enumerable.Range(1, 4)
                         from p4 in Enumerable.Range(1, 4)
                         from p5 in Enumerable.Range(1, 4)
                         from p6 in Enumerable.Range(1, 4)
                         from p7 in Enumerable.Range(1, 4)
                         from p8 in Enumerable.Range(1, 4)
                         from p9 in Enumerable.Range(1, 4)
                         select p1+p2+p3+p4+p5+p6+p7+p8+p9).ToList();

            var colin = (from p1 in Enumerable.Range(1, 6)
                         from p2 in Enumerable.Range(1, 6)
                         from p3 in Enumerable.Range(1, 6)
                         from p4 in Enumerable.Range(1, 6)
                         from p5 in Enumerable.Range(1, 6)
                         from p6 in Enumerable.Range(1, 6)
                         select p1+p2+p3+p4+p5+p6).ToList();

            double prob = (from p1 in Enumerable.Range(9, 28).AsParallel()
                           from p2 in Enumerable.Range(6, 31)
                           where p1 > p2
                           select  (1.0*peter.Count(x => x == p1)*
                                        colin.Count(x => x == p2))/
                             (1.0*peter.Count() * colin.Count())
                           ).Sum();

            Console.Write(Math.Round(prob,7));
            Console.Read();
        }
    }
}

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 08/03/2010, in C#, Project Euler and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s