Author Archives: MantasCode

C#: Project Euler Solution to Problem 92

http://projecteuler.net/problem=92

Problem 92

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

44 – 32 – 13 – 10 – 1 – 1
85 – 89 – 145 – 42 – 20 – 4 – 16 – 37 – 58- 89

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?

static void Main(string[] args)
{
    DateTime dt1 = DateTime.Now;
    int count89 = 0;
    for (int j = 1; j < 10000000; j++)
    {
        double currentNum = j;
        while (true)
        {
            double returnedSum = getNextNum(currentNum);
            currentNum = returnedSum;
            if (returnedSum == 1)
                break;
            if (returnedSum == 89)
            {
                count89++;
                break;
            }
        }
    }
    Console.WriteLine("Chains that end in 89 : "+count89);
    DateTime dt2 = DateTime.Now;
    Console.WriteLine("time "+ (dt2-dt1));
}
public static double getNextNum(double num)
{
    double sum = 0;
    string currentNum = "" + num;
    for (int i = 0; i < currentNum.Length; i++)
    {
        double numSquare = int.Parse(currentNum[i].ToString());
        sum += Math.Pow(numSquare, 2.00);
    }
    return sum;
}

C#: Project Euler Solution to Problem 54

Another fun Project Euler Problem, Number 54. Poker Problem!

http://projecteuler.net/problem=54

In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:

High Card: Highest value card.
One Pair: Two cards of the same value.
Two Pairs: Two different pairs.
Three of a Kind: Three cards of the same value.
Straight: All cards are consecutive values.
Flush: All cards of the same suit.
Full House: Three of a kind and a pair.
Four of a Kind: Four cards of the same value.
Straight Flush: All cards are consecutive values of same suit.
Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

The cards are valued in the order:
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.

The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1’s cards and the last five are Player 2’s cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player’s hand is in no specific order, and in each hand there is a clear winner.

How many hands does Player 1 win?

Although the below c# solution will get you the answer to the Euler Problem, it is still incomplete, and needs extra logic to score between high ranking hands.

Continue reading

C#: Project Euler Solutions to Problems 29, 30, and 34

http://projecteuler.net

Problem 29

How many distinct terms are in the sequence generated by a^b for 2 (le) a (le) 100 and 2 (le) b (le) 100?

LinkedList<double> distinct_values = new LinkedList<double>();
for (int i = 2; i <= 100; i++)
{
    for ( int j = 2 ; j <= 100; j ++)
    {
        double temp = Math.Pow(i, j);
        if (!distinct_values.Contains(temp))
        {
            distinct_values.AddLast(temp);
            Console.WriteLine(temp);
        }
    }
}
Console.WriteLine("Total : " + distinct_values.Count );

Problem 30

Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

double super_sum = 0;
for (int j = 2; j &lt; 1000000; j++)
{
    int num = j;
    double sum_of_dig = 0;
    string num_string = num.ToString();
    for (int i = 0; i &lt; num_string.Length; i++)
    {
        double pow = int.Parse(num_string[i].ToString());
        sum_of_dig += Math.Pow(pow, 5);
    }
    if (sum_of_dig == num)
        super_sum += sum_of_dig;
}
Console.WriteLine("Final Sum :"+ super_sum);

Problem 34

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

static void Main(string[] args)
{
    long bigsum = 0;
    for (int q = 3; q < 1000000; q++)
    {
        long num = q;
        string num_String = num.ToString();
        long sum = 0;
        for (int j = 0; j < num_String.Length; j++)
        {
            int temp = int.Parse(num_String[j].ToString());
            sum += Factorial(temp);
        }
        if (num == sum)
            bigsum += num;
    }
    Console.WriteLine("Answer : " +bigsum);
}
 
public static long Factorial(long x)
{
    long fact = 1;
    long i = 1;
    while (i <= x)
    {
        fact = fact * i;
        i++;
    }
    return fact;
}

C#: Project Euler Solution to Problem 37

Project Euler Problem 37

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left to right and right to left.

NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

static void Main(string[] args)
{
    DateTime dt1 = DateTime.Now;
 
    int truncPrimeCount = 0;
    int truncSum = 0;
    for (int j = 1; j &lt; 1000000; j++)
    {
        if (isPrime(j))
        {
            string specialPrimeNumer = "" + j;
            bool primedelims = true;
            while (primedelims == true)
            {
                for (int i = 1; i &lt; specialPrimeNumer.Length; i++)
                {
                    int prime_chck = int.Parse(specialPrimeNumer.Remove(specialPrimeNumer.Length - i));
                    if (!isPrime(prime_chck))
                        primedelims = false;
                }
                for (int i = 1; i &lt; specialPrimeNumer.Length; i++)
                {
                    int prime_chck = int.Parse(specialPrimeNumer.Remove(0, i));
                    if (!isPrime(prime_chck))
                        primedelims = false;
                }
 
                if (primedelims == true)
                {
                    truncPrimeCount++;
                    Console.WriteLine("Trunc prime #    : " + specialPrimeNumer);
                    if (truncPrimeCount &gt; 4)
                        truncSum += int.Parse(specialPrimeNumer);
                    if (truncPrimeCount == 15)
                        j = 1000001;
                    primedelims = false;
                }
            }
        }
    }
    Console.WriteLine("                 Sum :" +truncSum);
    DateTime dt2 = DateTime.Now;
    Console.WriteLine("Time : " +(dt2 - dt1));
}
 
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i &lt; n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

C#: Project Euler Solution to Problem 35

Project Euler Problem #35

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.

There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.

How many circular primes are there below one million?

static void Main(string[] args)
        {
            DateTime d1 = DateTime.Now;
            LinkedList<int> unique_CirclePrime = new LinkedList<int>();
            LinkedList<int> tempList = new LinkedList<int>();
            int currentPrime = 1;
            while (currentPrime <= 1000000)
            {
                string initNum2Rotate = currentPrime.ToString();
                int c = 0;
                int placeHolder = 0;
                for (int j = 0; j < initNum2Rotate.Length; j++)
                {
                    int previousdisplay = 0;
                    string displayString = "";
                    for (int i = 0; i < initNum2Rotate.Length; i++)
                    {
                        if (placeHolder == initNum2Rotate.Length)
                            placeHolder = 0;
                        int display = (placeHolder + c);
                        if (display == initNum2Rotate.Length)
                            display = 0;
 
                        if (display > initNum2Rotate.Length)
                            display = previousdisplay + 1;placeHolder++;
                        string gluestring = initNum2Rotate[display].ToString();
                        previousdisplay = display;
                        displayString += gluestring;
                    }
                    c++;
                    tempList.AddLast( int.Parse(displayString) );
                }
                bool allprimes = false;
                foreach (int item in tempList)
                {
                    if (isPrime(item))
                        allprimes = true;
                    else
                    {
                        allprimes = false;
                        break;
                    }
                }
                if (allprimes)
                {
                    foreach (int item in tempList)
                    {
                        if (!unique_CirclePrime.Contains(item))
                            unique_CirclePrime.AddLast(item);
                    }
                }
                tempList.Clear();
                currentPrime++;
            }
 
            int counter = 1;
            foreach (var item in unique_CirclePrime)
            {
                Console.WriteLine(item + "       " + isPrime(item) + "       " + counter);
                counter++;
            }
            DateTime d2 = DateTime.Now;
 
            Console.WriteLine("Total Length of Unique Circular Primes : "+ unique_CirclePrime.Count);
            Console.WriteLine("time : " + (d2 - d1));
        }
 
        public static bool isPrime(int n)
        {
            if (n == 1)
                return false;
            if (n == 2)
                return true;
            for (int i = 2; i < n; ++i)
            {
                if ((n % i) == 0)
                    return false;
            }
            return true;
        }

C#: Project Euler Solutions to Problems 14, 16, and 22

More ProjectEuler.net fun.

Problem 14

The following iterative sequence is defined for the set of positive integers:

n n/2 (n is even)
n 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 – 40 – 20 – 10 – 5 – 16 – 8 – 4 – 2 – 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

static void Main(string[] args)
{
    //populate dictionary with steps and number
    Dictionary dictionary = new Dictionary();
    for (int i = 1; i &lt; 1000000; i++)
    {
        Int64 mySteps = getSteps(i);
        if ( !dictionary.ContainsKey(mySteps) )
        {
            dictionary.Add(mySteps,i);
        }
    }
    //sort the dictionary from least amount of steps to most
    var list = dictionary.Keys.ToList();
    list.Sort();
    foreach (var key in list)
    {
        Console.WriteLine("Number : {1} \t Steps : {0}", key, dictionary[key]);
    }
}
 
public static Int64 getSteps(Int64 i)
{
    Int64 startInt = i;
    Int64 steps = 0;
    while (true)
    {
        if (startInt == 1)
            break;
        steps++;
        if (startInt % 2 == 0)
            startInt = startInt / 2;
        else
            startInt = (startInt * 3) + 1;
    }
    return steps;
}

Problem 16

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

//2^1000 string
string two_pow_1000 = 
@"10 715 086 071 862 673 209 484 250 490 600 018 105 614 048 117 055 336 074 437 503 883 703 510 511 249 361 224 931 983 788 156 958 581 275 946 729 175 531 468 251 871 452 856 923 140 435 984 577 574 698 574 803 934 567 774 824 230 985 421 074 605 062 371 141 877 954 182 153 046 474 983 581 941 267 398 767 559 165 543 946 077 062 914 571 196 477 686 542 167 660 429 831 652 624 386 837 205 668 069 376";
int sum = 0;
for (int i = 0; i &lt; two_pow_1000.Length; i++)
{
    if (two_pow_1000[i] != ' ' )
        sum += Int32.Parse(two_pow_1000[i].ToString());
}
Console.WriteLine(sum);

Problem 22

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 X 53 = 49714.

What is the total of all the name scores in the file?

StreamReader nameStream;
string fullBook = "";
nameStream = File.OpenText("C:\\Euler\\names.txt");
fullBook = nameStream.ReadToEnd();
nameStream.Close();
string[] names = fullBook.Split(',');
Array.Sort(names);
int totalSum = 0;
for (int i = 0; i &lt; names.Length; i++)
{
    int namePosition = (i + 1);
    string name = names[i].Replace('"', ' ').Trim();
    int lettersum = 0;
    for (int j = 0; j &lt; name.Length; j++)
    {
        lettersum += (int)(name[j] - 64);
    }
    totalSum += (lettersum * (i + 1));
}
Console.WriteLine("Answer : "+ totalSum);

C#: Project Euler Solutions to Problems 2, 5, 6, and 7

ProjectEuler.net is a fun website which posts computational problems.  I’ve chosen several easy ones to solve using C#.

Problem 2

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

int fibNum = 0;
int prevNum = 1;
int sum = 0;
while (true)
{
    int temp = fibNum;
    fibNum = prevNum;
    prevNum = temp + prevNum;
 
    if (fibNum &gt; 4000000)
        break;
 
    if (fibNum % 2 == 0)
    {
        sum += fibNum;
    }
}
Console.WriteLine("SUM : " + sum);

Problem 5

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

bool bDivisibleby10 = false;
int currentNum = 0;
while (true)
{
    currentNum++;
    for (int i = 1; i <= 20; i++)
    {
        if ((currentNum % i) == 0)
        {
            bDivisibleby10 = true;
        }
        else
        {
            bDivisibleby10 = false;
            break;
        }
    }
    if (bDivisibleby10)
    {
        Console.WriteLine("Answer : " +currentNum);
        break;
    }
}

Problem 6

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

int sum_of_squares = 0;
for (int i = 1; i <= 100; i++)
{
    sum_of_squares +=  (int)Math.Pow(i, 2);
}
int square_of_sum = 0;
for (int i = 1; i <= 100; i++)
{
    square_of_sum += i;
}
Console.WriteLine("Difference : " + 
    ( Math.Pow(square_of_sum, 2) - sum_of_squares));

Problem 7

What is the 10,001st prime number?

static void Main(string[] args)
{
    int currentPrime = 1;
    int primeNum = 0;
    while (true)
    {
        if (isPrime(currentPrime))
            primeNum++;
 
        if (primeNum == 10001)
            break;
        currentPrime++;
    }
    Console.WriteLine(  currentPrime  );
}
public static bool isPrime(int n)
{
    if (n == 1) 
        return false;
    if (n == 2) 
        return true;
    for (int i = 2; i &lt; n; ++i)
    {
        if ((n % i) == 0) 
            return false;
    }
    return true;
}

C#: Simple spider to crawl over numeric URL parameters.

How to loop over a list of numeric IDs within the URL, using C#.

Some websites use numeric identifiers in order to retrieve and display information about a parictular product, article, service, or whatever.

So if you see a URL which ends in, or contains something like this:

http://www.example.com/products/product_detail.aspx?id=12345

Chances are that the 12345 represents the identifier used to query a database and return formatted information (html) to your web browser.

So how can we get the returned html into a string?
simple!

WebClient myClient = new WebClient();
string sReturnedHtml = myClient.DownloadString
("http://www.example.com/products/product_detail.aspx?id=12345");

That’s it. Now you probably want to apply some regular expressions to the returned html string, to do things like: remove tags, or parse specific chunks. (I know, I know, parsing html using regular expressions will make babies cry) Then, save it into your own XML or something.

I can’t show you how to parse chunks of the returned HTML in this example, because different websites will return their own unique html structures. But you can read more on how to parse the content of a string between two string fragments here C#: Parsing a string using Regular Expressions (Regex) (Just look for patterns surrounding what you need).

Here is how you would loop from ID 1 through ID 99999, and save the information for each id into a text file, with some tags to separating out each ID.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
 
namespace Simple_Spider
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 100000; i++)
            {
 
                //Use a try because some product ID's might not be public
                //so even though they exist in the database, the website
                //might not want to show them
                try
                {
                    Console.WriteLine("Parsing ID :" + i);
                    WebClient myClient = new WebClient();
                    string sReturnedHtml = myClient.DownloadString
  ("http://www.example.com/products/product_detail.aspx?id=" + i);
 
                    //Here is where you'd manipulate (sReturnedHtml)
                    //the returned string into your own structure
                    //or take out only what you need.
 
                    //Append your parsed content into a txt file
                    // inside directory C:\SPIDER\
                    StreamWriter streamWrite;
                    streamWrite = File.AppendText("C:\\SPIDER\\log.txt");
                    streamWrite.WriteLine
                        ("<content id=\""+i+"\">\r\n"+sReturnedHtml+"\r\n </content>");
                    streamWrite.Close();
 
                }
                catch (Exception x)
                {
                    //bad ID
                    Console.WriteLine("ERROR 404 maybe");
                }
 
                //This will pause the spider between each ID
                //Make it sleep a second, so your not 
                //bombarding servers with requests
                Thread.Sleep(1000);
            }
 
        }
    }
}

Ontology: How to use RadLex Ontology to Index Content?

In this post, I will demonstrate how you can text mine your own content with a Protege Ontology.  This is a high level post about using ontologies.

Get the name and unique identifier of every concept within the structured ontology.  Then  parse various digital formats (word documents, pdfs, text files, or database columns) for each concept name.  Lastly, record the concept name found, concept id, its frequency of occurrence, and an identifier for which content I found it in.

The following diagram parses a Microsoft Word doc for ontology concepts.

Now you can start playing with the datasets!  Have Fun!  :D

Javascript: Plot point on GoogleMaps using coordinates Latitude and Longitude

How to place a tack  or knife a map. Throw darts programmatically .

a google map

Here is the javascript,

you need your own google maps api key.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
 
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=(YOUR_OWN_KEY)&sensor=false">
</script>
 
<script type="text/javascript">
 
function initialize() 
{
 
var myOptions = {center: new google.maps.LatLng(38.4686, -123.0028),
 zoom: 12,
 mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
 
var lat = 38.4686;		
var long = -123.0028;
 marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map
});
 
}	  
</script>
</head>
 
<body onload="initialize()">
<div id="map_canvas" style="width:60%; height:60%"></div>
</body>
</html>

Now you can write your name on islands! : D