Category Archives: C#

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);
            }
 
        }
    }
}

C#: Generate 10 unique integers (1-10) using only 10 steps

In this fun little program I force my computer to randomly generate a list of ten unique numbers, one through ten, using only 10 steps.

I run the program until it randomly meets all these conditions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace SandCastlePractice
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Generate a distinct list of 10 random numbers,"
                +" ranging from 1 to 10, with the lowest amount of steps (10)");
            DateTime timeStart = DateTime.Now;
            Console.WriteLine("Time Started : "+ timeStart.TimeOfDay+"\r\n");
 
            //Counter for total times it will try
            int Total_Iterations = 0;
            //Decrementor for lowest amount of steps to create distinct list
            int lowestStep = 10000;
            //int used to see if lowest step changed
            int laststep = 0; 
            //display list when lowest steps are achieved
            LinkedList<int> displayList = new LinkedList<int>();
 
            //while the lowest steps arnt 10, keep trying
            while (lowestStep != 10)
            {
                Total_Iterations++;
                //steps counter
                int iSteps = 0;
                //bool to check if list of 10 is distinct
                bool isListDistinct = false;
                //temp LinkedList to be populated over and over
                LinkedList<int> numList = new LinkedList<int>();
                //create random number object
                Random random = new Random();
                while (!isListDistinct)
                {
                    ++iSteps;
                    //get a random number 0 - 10
                    int randomNumber = random.Next(0, 10);
                    //increment it by one so its 1-10, instead of 0-9
                    randomNumber++;
                    //if temp LinkedList doesn't contain generated int, add it
                    if (!numList.Contains(randomNumber))
                        numList.AddLast(randomNumber);
                    //when the list has 10 elements stop looping
                    if (numList.Count == 10)
                    {
                        isListDistinct = true;
                        //check if lowest amount of step is less then previous
                        if (iSteps < lowestStep)
                            lowestStep = iSteps;
                    }
                }
                //if lowest amount of steps got lower
                if (laststep != lowestStep)
                {
                    //Display new low
                    Console.WriteLine("lowest steps so far : " + lowestStep);
                    //when steps taken are 10, set current temp LinkedList 
                    //to Display List
                    if (lowestStep == 10)
                        displayList = numList;
 
                }
                laststep = lowestStep;
                isListDistinct = false;
            }
 
            Console.WriteLine("---------------------\r\n");
            //display the distinct list of ten, that only took 10 steps to generate
            foreach (var num in displayList)
            {
                Console.Write(num + " ");
            }
            Console.WriteLine();
            Console.WriteLine("How many times did it have to try?  " + 
                Total_Iterations.ToString("#,##0"));
            DateTime timeFinish = DateTime.Now;
            Console.WriteLine("How Long did it take?               "+  
                (timeFinish-timeStart)   );
        }
    }
}

C#: Sort lists of bits by which end they congregate at.

Say, you’ve got several lists which contain two potential values for each item, such as:

10010
11000
00101

and you’d like to sort them like a seesaw, from most weighed down on the right to most weighed down on the left.

 


and sort them like so 0010110010, 11000

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Polarity
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("indeed.");
            Random random = new Random();
            LinkedList[] arrayLL = new LinkedList[10];
 
            //Make 10 lists: each with 10 items
            //for each set of items there must be three 1's, in random locations
            //then sort the ten lists by their closeness towards the end 
 
            for (int i = 0; i &lt; 10; i++)
            {
                LinkedList distinctOrder = new LinkedList();
                while (distinctOrder.Count &lt; 10)
                {
                    int randomNumber = random.Next(0, 10);
                    if (!distinctOrder.Contains(randomNumber))
                        distinctOrder.AddLast(randomNumber);
                }
                Console.WriteLine();
 
                //now that i have my distinct list random 1-10 order
                //make 0,1,2 into 1's and the rest into 0's
                LinkedList polList = new LinkedList();
                foreach (var num in distinctOrder)
                {
                    if (num == 0 || num == 1 || num == 2)
                        polList.AddLast(1);
                    else
                        polList.AddLast(0);
                }
                foreach (var num in polList)
                {
                    Console.Write(num + " ");
                }
                arrayLL[i] = polList;
            }
 
            Console.WriteLine("\r\n-------------------");
            Dictionary dictionary = new Dictionary();
 
            //figure out the score of each line and add it to dictionary
            //the position of the 1's indicidate their score towards the end
            for (int i = 0; i &lt; arrayLL.Length; i++)
            {
                int[] thisLine = arrayLL[i].ToArray();
                int sum = 0;
                string line = "";
                for (int k = 0; k &lt; thisLine.Length; k++)                 
                {                    
                         line += " " + thisLine[k];                    
                         if (thisLine[k] == 1)                         
                                  sum += k;                 
                 }                 
                 Console.WriteLine(line+"    "+sum);                
                 //add string of 10 to dictionary object                
                 //Warning! this will crash if the randomized string repeats                
                dictionary.Add(line, sum);                                 
          }             
           Console.WriteLine("-------------------");             
            //sort lines from highest score to lowest             
            var sortedDict = (from entry in dictionary orderby entry.Value descending select entry).ToDictionary(pair =&gt; pair.Key, pair =&gt; pair.Value);
            foreach (var strKey in sortedDict.Keys)
                Console.WriteLine(strKey);
 
        }
    }
}

C#: Hashtable Inversion, how to invert a Hashtable

This quick project is example of simple Data transformation.  Hashtable’s values containing a comma deliminated list of strings gets turned into a distinct list of keys in another Hashtable.  And, the numbers (keys of initial Hashtable) are accumulated into the values of the new Hashtable.  Creating an inverted Hashtable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace HashInversion
{
    class Program
    {
        static void Main(string[] args)
        {
            Hashtable num_2_Letters_Hash = new Hashtable();
            Hashtable letters_2_num_Hash = new Hashtable();
 
            num_2_Letters_Hash.Add(1, "a,c,d");
            num_2_Letters_Hash.Add(6, "d,e");
            num_2_Letters_Hash.Add(13, "a,d,j");
            num_2_Letters_Hash.Add(29, "c,e,d");
            num_2_Letters_Hash.Add(7, "j");
            num_2_Letters_Hash.Add(9, "e,c,a");
            num_2_Letters_Hash.Add(11, "c,d,f,j");
 
            foreach (var key in num_2_Letters_Hash.Keys)
            {
                string content = num_2_Letters_Hash[key].ToString();
                string [] letters = content.Split(',');
                for (int i = 0; i &lt; letters.Length; i++)
                {
                    if ( letters_2_num_Hash.ContainsKey(letters[i].ToString()))
                    {
                        string previous_content = letters_2_num_Hash[letters[i]].ToString();
                        letters_2_num_Hash[letters[i]] = previous_content + "," + key;
                    }
                    else
                    {
                        letters_2_num_Hash.Add(letters[i],""+key);
                    }
                }
            }
 
            Console.WriteLine();
 
            Console.WriteLine("before");
            foreach (var key in num_2_Letters_Hash.Keys)
            {Console.WriteLine(key + "   " + num_2_Letters_Hash[key]);}
 
            Console.WriteLine("after");
            foreach (var key in letters_2_num_Hash.Keys)
            {Console.WriteLine(key + "   " + letters_2_num_Hash[key]);}
        }
    }
}

C#: How to read from Microsoft PowerPoint file ppt

Get the text out of each PowerPoint slide.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
 
namespace readPPT
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
            Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
            Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(@"C:\PPT\myPowerpoint.pptx");
            string presentation_text = "";
            for (int i = 0; i < presentation.Slides.Count; i++)
            {
                foreach (var item in presentation.Slides[i+1].Shapes)
                {
                    var shape = (PowerPoint.Shape)item;
                    if (shape.HasTextFrame == MsoTriState.msoTrue)
                    {
                        if (shape.TextFrame.HasText == MsoTriState.msoTrue)
                        {
                            var textRange = shape.TextFrame.TextRange;
                            var text = textRange.Text;
                            presentation_text += text+" ";
                        }
                    }
                }
            }
            PowerPoint_App.Quit();
            Console.WriteLine(presentation_text);
        }
    }
}