Category Archives: C#

C#: Parsing Horses.

Horserace

My goal with this post is to parse out all the horses which came in 1st to 3rd place from each race that took place at Arlington Park this season.

The website http://www.arlingtonpark.com/racing-handicapping/equibase/charts provides a calendar which links to the result file for each race date from the past. Clicking on a particular date will link you to a pdf which contains various statistics.

calendar

So lets download all of these programmatically. To achieve this, I wrote a small program to iterate over dates in the uri, requesting every race date pdf file.

Then, I save them into a folder on my c: drive called \HORSEDATA\. I also, wait 1 -3 second before each request, alternate the web client’s header, and delete the downloaded file if it is too small (No Race happened on that date).

DateTime Today = DateTime.Now;
int randomWait = 0;
Random random = new Random();
for (int i = 0; i < 200; i++)
{
    randomWait = random.Next(1000, 3000);
    Thread.Sleep(randomWait);
    Console.WriteLine("Downloading : " + Today.ToString("d"));
    Today =  Today.AddDays( -1 );
    try
    {
        using (WebClient client = new WebClient())
        {
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.370"+i+";)");
client.DownloadFile("http://www.equibase.com/premium/eqbPDFChartPlus.cfm?RACE=A&BorP=P&TID=AP&CTRY=USA&DT=" 
    + Today.ToString("d") + "&DAY=D&STYLE=EQB", @"C:\HORSEDATA\\" + Today.ToString("MM-dd-yy") + ".pdf");
        }
    }
    catch (Exception x)
    {Console.WriteLine("No Race on this Date.");}
    FileInfo f = new FileInfo(@"C:\HORSEDATA\\" + Today.ToString("MM-dd-yy") + ".pdf");
    long s1 = f.Length;
    Console.WriteLine(s1.ToString());
    if (s1 < 4000)
        File.Delete(@"C:\HORSEDATA\\" + Today.ToString("MM-dd-yy") + ".pdf");
}

Now your \HORSEDATA\ folder should contain the proper pdfs.
horsedatapdf

Next, read through all the race date PDFs. For each PDF, I want to get the names of horses which came in 1st to 3rd place, and count up the amount of times each unique horse at least showed.

3 horse parse

Using iTextSharp library to read the PDFs and count up my horses.

using iTextSharp;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.pdf.parser;
using System.Text.RegularExpressions;
Console.BufferHeight = 6000;
Dictionary<string, int> dictHorseShowCount = new Dictionary<string, int>();
LinkedList uniqueHorse = new LinkedList();
string[] filePaths = Directory.GetFiles(@"c:\HORSEDATASET\");
foreach (string file in filePaths)
{
    Console.WriteLine("Reading : " + file);
    PdfReader reader = new PdfReader(file); 
    StringWriter output = new StringWriter();  
    for (int i = 1; i <= reader.NumberOfPages; i++)
        output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
    Regex regPattern = new Regex(@"Total WPS Pool(.*?)Copyright", RegexOptions.Singleline);
    MatchCollection matchX = regPattern.Matches(output.ToString());
    foreach (Match match in matchX)
    {
        Match match2 = Regex.Match(match.ToString(), @"Win Place Show(.*?)Wager Type", RegexOptions.Singleline);
        if (match2.Success)
        {
            string [] lineparts = Regex.Split(match2.ToString(),"\n");
            for( int i = 1; i < lineparts.Length - 1; i++ )
            {
                string horseOnly = Regex.Replace(lineparts[i].ToString(), "[^a-zA-Z -]", "");
                if (!uniqueHorse.Contains(horseOnly.Trim()))
                    uniqueHorse.AddLast(horseOnly.Trim());
                if (dictHorseShowCount.ContainsKey(horseOnly.Trim()))
                {
                    int existing_int = dictHorseShowCount[horseOnly.Trim()];
                    existing_int += 1;
                    dictHorseShowCount[horseOnly.Trim()] = existing_int;
                }
                else
                    dictHorseShowCount[horseOnly.Trim()] = 1;
            }
        }
    }
}
var sortedDict = (from entry in dictHorseShowCount orderby entry.Value ascending select entry)
.ToDictionary(pair => pair.Key, pair => pair.Value);
foreach (string key in sortedDict.Keys)
    Console.WriteLine(key + "   "   + sortedDict[key]);
Console.WriteLine("");
Console.WriteLine("Distinct Horse Showed : " + uniqueHorse.Count);
Console.WriteLine("");

Output
outputHORSES

C#: Parse a Sentence Containing a Word from Text using Regular Expressions.

Recently, I had received an email from someone asking me how to obtain all sentences containing a specific word. So, I made this quick post. The code below shows how to use regular expressions to parse all sentences from text, then check to see if the sentence contains a specific word.

//Look for sentences containing the word "bank"
string word = "bank";
//Text String
string fulltext = @"Starting in the early 1960s federal banking regulators interpreted provisions of the Glass–Steagall Act to permit commercial banks and especially commercial bank affiliates to engage in an expanding list and volume of securities activities. By the time the affiliation restrictions in the Glass–Steagall Act were repealed through the Gramm–Leach–Bliley Act of 1999 (GLBA), many commentators argued Glass–Steagall was already “dead.” Most notably, Citibank’s 1998 affiliation with Salomon Smith Barney, one of the largest US securities firms, was permitted under the Federal Reserve Board’s then existing interpretation of the Glass–Steagall Act. President Bill Clinton publicly declared ""the Glass–Steagall law is no longer appropriate."" Many commentators have stated that the GLBA’s repeal of the affiliation restrictions of the Glass–Steagall Act was an important cause of the late-2000s financial crisis.  Some critics of that repeal argue it permitted Wall Street investment banking firms to gamble with their depositors' money that was held in affiliated commercial banks. Others have argued that the activities linked to the financial crisis were not prohibited (or, in most cases, even regulated) by the Glass–Steagall Act. Commentators, including former President Clinton in 2008 and the American Bankers Association in January 2010, have also argued that the ability of commercial banking firms to acquire securities firms (and of securities firms to convert into bank holding companies) helped mitigate the financial crisis.";
 
//Match Collection for every sentence
MatchCollection matchSentences = 
    Regex.Matches(fulltext, @"([A-Z][^\.!?]*[\.!?])");
//Alternative pattern :  @"(\S.+?[.!?])(?=\s+|$)"
 
//counter for sentences.
int foundSentenceWithWord = 0;
foreach (Match sFound in matchSentences)
{
    foreach (Capture capture in sFound.Captures)
    {
        string current_sentence = capture.Value;
        //if you don't want to match for words like 'bank'er  or  'bank'ing
        //use the word boundary "\b"
        //change this pattern to   @"\b"+word+@"\b"
        Match matchWordInSentence = 
            Regex.Match(capture.Value, word, RegexOptions.IgnoreCase);
        if (matchWordInSentence.Success)
        {
            Console.WriteLine("Sentence Found Containing '" + word+"' :");
            Console.WriteLine(current_sentence); Console.WriteLine();
            foundSentenceWithWord++;
        }
    }
}
Console.WriteLine();
Console.WriteLine("Found " + foundSentenceWithWord 
    + " Sentences Containing the word '" + word + "'");
Console.WriteLine();

Output:

C#: Split GIF frames into PNGs using ImageMagick

How to split apart a GIF image frame by frame, and save each frame as PNG into a sub-folder.

To achieve this I will be using ImageMagick
http://www.imagemagick.org/

Download, Install and locate an executable named convert.exe

I created a folder on my C: Drive called
/ImageConversion/

Place your GIFs into the ImageConversion Folder, also copy convert.exe into there as well. So the folder should look like this:

Execute this code:

//get all files in folder
string[] files = Directory.GetFiles(@"c:\ImageConversion\");
 
//loop through each file
foreach (string file in files)
{
    //check if .GIF
    string ext = Path.GetExtension(file);
    if (ext == ".gif")
    {
        Console.WriteLine("Splitting : "+file);
        //Get the name of the file without extension
        string filenameNoExt = Path.GetFileNameWithoutExtension(file);
        //Get the file name with extention
        string filenameExt = Path.GetFileName(file);
        Console.WriteLine();
        //Create a Sub Directory with the same as the GIF's filename
        Directory.CreateDirectory(@"c:\ImageConversion\"+filenameNoExt);
        Process imProcess = new Process();
        //Arguments
        string im_command = @"c:\ImageConversion\"
        + filenameExt + @" -scene 1 +adjoin -coalesce c:\ImageConversion\" + filenameNoExt + @"\" + filenameNoExt + ".png";
        imProcess.StartInfo.UseShellExecute = false;
        imProcess.StartInfo.RedirectStandardOutput = true;
        imProcess.StartInfo.FileName = @"c:\ImageConversion\convert";
        imProcess.StartInfo.Arguments = im_command;
        imProcess.Start();
        imProcess.WaitForExit();
    }
}

That’s it, you’re done.
Now the ImageConversion folder should be populated with a folder for every gif containing every frame as an individual png.

C#: Programmatically download all Images from a website and save them locally.

For this example, I will be downloading all the .gifs from a specific page on imgur. Then, I will save them into a folder called _Images.

This is the url to the specific page I will be downloading images from http://imgur.com/a/GPlx4

What the website looks like:

Below is C# code that will:
-use a WebClient.DownloadString() to download the html into a string
-parse out specific image links from the returned html string using regular expressions
-use another WebClient.DownloadFile() to download each image link parsed

WebClient wchtml = new WebClient();
string htmlString = wchtml.DownloadString("http://imgur.com/a/GPlx4");
int mastercount = 0;
Regex regPattern = new Regex(@"http://i.imgur.com/(.*?)alt=""", RegexOptions.Singleline);
MatchCollection matchImageLinks = regPattern.Matches(htmlString );
 
foreach (Match img_match in matchImageLinks)
{
    string imgurl = img_match.Groups[1].Value.ToString();
    Regex regx = new Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?",
    RegexOptions.IgnoreCase);
    MatchCollection ms = regx.Matches(imgurl);
    foreach (Match m in ms)
    {
        Console.WriteLine("Downloading..  "  + m.Value);
        mastercount++;
        try
        {
            WebClient wc = new WebClient();
            wc.DownloadFile(m.Value, @"C:\_Images\bg_" + mastercount + ".gif");
            Thread.Sleep(1000);
        }
        catch (Exception x)
        {
            Console.WriteLine("Failed to download image.");
        }
        break;
    }
}

Output: C:\_Images

C#: Parse a website and save specific content as XML.

In this tutorial I will show you how to iterate through a website using a WebClient,  Save each page’s content into a string, parse it using regular expressions, and save it as XML.

I will be parsing airplane data from airliners.net

Here is a picture of what the website looks like.

Get started with a .NET C# Console application and create a WebClient.

Use the URL and Output the html returned.

WebClient wc = new WebClient();
string htmlString = wc.DownloadString("http://www.airliners.net/aircraft-data/stats.main?id=2");
Console.WriteLine(htmlString);

Lets take a look at both  the console output and the source of the page to make sure we got the right html back.

Console and Page Source

Success, we found the Airplane title!  Now lets see if we can parse it, and only it, from the entire string of html.

Try to see if there is a pattern that’s unique to what you need.

WebClient wc = new WebClient();
string htmlString = wc.DownloadString("http://www.airliners.net/aircraft-data/stats.main?id=2");
Match mTitle = Regex.Match(htmlString, @"<center><h1>(.*?)</h1>");
if (mTitle.Success)
{
    string airplaneTitle = mTitle.Groups[1].Value;
    Console.WriteLine(airplaneTitle);
}

Success.

Now lets get Country of Origin and the other categories.

string airplaneCountry = "";
Match mCountry = Regex.Match(htmlString, @"<b>Country of origin</font>(.*?)<p>", RegexOptions.Singleline);
if (mCountry.Success)
{
     airplaneCountry = mCountry.Groups[1].Value;
     Console.WriteLine(airplaneCountry);
}
Console.WriteLine("***************************************************************");
//manicure the pattern string
//Replace everything before the last (greater than) sign with and empty string
airplaneCountry = Regex.Replace(airplaneCountry, "(.*?)>", "").Trim();
Console.WriteLine(airplaneCountry);

Now I am tired of typing, so lets make a method for everything else.

static void Main(string[] args)
{
 
    WebClient wc = new WebClient();
    string htmlString = wc.DownloadString("http://www.airliners.net/aircraft-data/stats.main?id=2");
 
    Console.WriteLine("Name       :"+ parsePattern(@"<center><h1>(.*?)</h1>",htmlString));
    Console.WriteLine("Country    :" + parsePattern(@"<b>Country of origin</font>(.*?)<p>", htmlString));
    Console.WriteLine("Powerplants:" + parsePattern(@"<b>Powerplants</font>(.*?)<p>", htmlString));
    Console.WriteLine("Performance:" + parsePattern(@"<b>Performance</font>(.*?)<p>", htmlString));
    Console.WriteLine("Weights    :" + parsePattern(@"<b>Weights</font>(.*?)<p>", htmlString));
    Console.WriteLine("Dimentions :" + parsePattern(@"<b>Dimensions</font>(.*?)<p>", htmlString));
    Console.WriteLine("Capacity   :" + parsePattern(@"<b>Capacity</font>(.*?)<p>", htmlString));
    Console.WriteLine("Type       :" + parsePattern(@"<b>Type</font>(.*?)<p>", htmlString));
    Console.WriteLine("Production :" + parsePattern(@"<b>Production</font>(.*?)<p>", htmlString));
 
    //lol   :D   Damn this History!
    //Console.WriteLine(parsePattern(@"<b>History</font>(.*?)<table border=0 cellpadding=1 cellspacing=0 >", htmlString));
    //History breaks my method pattern cause there's too many <p>'s
    //Doing History Manually, Due to Different Pattern.
    Match mHistory = Regex.Match(htmlString, @"<b>History</font>(.*?)<table border=0 cellpadding=1 cellspacing=0 >", RegexOptions.Singleline);
    if (mHistory.Success)
    {
        string strContent = mHistory.Groups[1].Value;
        //Google your problems "C# regex to remove html" - thanks stackoverflow
        //Get @"<[^>]*>"
        strContent = Regex.Replace(strContent, @"<[^>]*>", "").Trim();
        Console.WriteLine("History : " + strContent);
    }
}
public static string parsePattern(string pat, string htmlString)
{
    Match mCategory = Regex.Match(htmlString, @pat, RegexOptions.Singleline);
    if (mCategory.Success)
    {
        string strContent = mCategory.Groups[1].Value;
        if (strContent.Contains('>'))
        {
            strContent = Regex.Replace(strContent, "(.*?)>", "").Trim();
            return strContent;
        }
        else
            return strContent;
    }
    return "";
}

Now lets save everything into xml :D
I Created a Folder in my C: Drive called C:\Airplanes\
Iterate through each page and save the content.

Here’s the full Code to do the Whole Website:

static void Main(string[] args)
{
    //Since we don't want to hold a glock up to the webserver's dome piece:
    //Let's pretend to be a human who goes to each page within 1 - 3 seconds randomly.
    WebClient wc = new WebClient();
    int pageCount = 1;
    int randomWait = 0;
    Random random = new Random();
    while (true)
    {
        randomWait = random.Next(1000, 3000);
        Thread.Sleep(randomWait);
        string htmlString = wc.DownloadString("http://www.airliners.net/aircraft-data/stats.main?id=" + pageCount);
        ReadAndAppend(htmlString);
        pageCount++;
        Console.WriteLine("Saving :" + pageCount);
    }
}
public static void ReadAndAppend(string htmlString)
{
    string name = parsePattern(@"<center><h1>(.*?)</h1>", htmlString);
    string country = parsePattern(@"<b>Country of origin</font>(.*?)<p>", htmlString);
    string power = parsePattern(@"<b>Powerplants</font>(.*?)<p>", htmlString);
    string perf = parsePattern(@"<b>Performance</font>(.*?)<p>", htmlString);
    string lb = parsePattern(@"<b>Weights</font>(.*?)<p>", htmlString);
    string dim = parsePattern(@"<b>Dimensions</font>(.*?)<p>", htmlString);
    string cap = parsePattern(@"<b>Capacity</font>(.*?)<p>", htmlString);
    string type = parsePattern(@"<b>Type</font>(.*?)<p>", htmlString);
    string prod = parsePattern(@"<b>Production</font>(.*?)<p>", htmlString);
    string hist = "";
    Match mHistory = Regex.Match(htmlString, @"<b>History</font>(.*?)<table border=0 cellpadding=1 cellspacing=0 >", RegexOptions.Singleline);
    if (mHistory.Success)
    {
        string strContent = mHistory.Groups[1].Value;
        strContent = Regex.Replace(strContent, @"<[^>]*>", "").Trim();
        hist = strContent;
    }
    //make the xml
    string xmlString = "<plane>";
    xmlString += "  <name>" + name + "</name>\r\n";
    xmlString += "  <country>" + country + "</country>\r\n";
    xmlString += "  <power>" + power + "</power>\r\n";
    xmlString += "  <perf>" + perf + "</perf>\r\n";
    xmlString += "  <lb>" + lb + "</lb>\r\n";
    xmlString += "  <dim>" + dim + "</dim>\r\n";
    xmlString += "  <cap>" + cap + "</cap>\r\n";
    xmlString += "  <type>" + type + "</type>\r\n";
    xmlString += "  <prod>" + prod + "</prod>\r\n";
    xmlString += "  <hist>" + hist + "</hist>\r\n";
    xmlString += "</plane>\r\n\r\n";
 
    //Show me the saves and count
    Console.WriteLine(xmlString);
 
    //save to C:\Airplanes\
    StreamWriter streamWrite;
    streamWrite = File.AppendText("C:\\Airplanes\\airData.xml");
    streamWrite.WriteLine(xmlString);
    streamWrite.Close();
}
 
public static string parsePattern(string pat, string htmlString)
{
    Match mCategory = Regex.Match(htmlString, @pat, RegexOptions.Singleline);
    if (mCategory.Success)
    {
        string strContent = mCategory.Groups[1].Value;
        if (strContent.Contains('>'))
        {
            strContent = Regex.Replace(strContent, "(.*?)>", "").Trim();
            return strContent;
        }
        else
            return strContent;
    }
    return "";
}

Heres the XML file Created.

C#: How to get correlation coefficient of two arrays Correl()

This simple example shows you how to get the correlation coefficient of two arrays.  Microsoft Excel and OpenOffice Calc has a function for this called CORREL() :

//Two arrays
double[] array1 = { 3, 2, 4, 5, 6 };
double[] array2 = { 9, 7, 12, 15, 17 };
 
double[] array_xy = new double[array1.Length];
double[] array_xp2 = new double[array1.Length];
double[] array_yp2 = new double[array1.Length];
for (int i = 0; i &lt; array1.Length; i++)
    array_xy[i] = array1[i] * array2[i];
for (int i = 0; i &lt; array1.Length; i++)
    array_xp2[i] = Math.Pow(array1[i], 2.0);
for (int i = 0; i &lt; array1.Length; i++)
    array_yp2[i] = Math.Pow(array2[i], 2.0);
double sum_x = 0;
double sum_y = 0;
foreach (double n in array1)
    sum_x += n;
foreach (double n in array2)
    sum_y += n;
double sum_xy = 0;
foreach (double n in array_xy)
    sum_xy += n;
double sum_xpow2 = 0;
foreach (double n in array_xp2)
    sum_xpow2 += n;
double sum_ypow2 = 0;
foreach (double n in array_yp2)
    sum_ypow2 += n;
double Ex2 = Math.Pow(sum_x, 2.00);
double Ey2 = Math.Pow(sum_y, 2.00);
 
double Correl = 
(array1.Length * sum_xy - sum_x * sum_y) /
Math.Sqrt((array1.Length * sum_xpow2 - Ex2) * (array1.Length * sum_ypow2 - Ey2));
 
Console.WriteLine("CORREL : "+ Correl);

C#: Project Euler Solution to Problem 27

http://projecteuler.net/problem=27

Considering quadratics of the form:

n² + an + b, where |a| < 1000 and |b| < 1000 where |n| is the modulus/absolute value of n e.g. |11| = 11 and |-4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.

static void Main(string[] args)
{
    //n² + an + b
    int maxprimes = 0;
    int maxproduct = 0;
    for (int a = 0; a < 1000; a++)
    {
        for (int b = 0; b < 1000; b++)
        {
            int prime = countPrime(a, b);
            if (maxprimes < prime)
            {
                maxprimes = prime;
                maxproduct= (-a*b );
            }
        }
    }
    Console.WriteLine(maxproduct);
}
 
public static int countPrime(int a, int b)
{
    int count = 0;
    int n = 0;
    while (true)
    {
        double result = Math.Pow(n, 2.00) - (a * n) + b;
        if (isPrime((int)result) && result >= 0)
            count++;
        else
            return count;
        n++;
    }
}
 
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 Solution to Problem 32

http://projecteuler.net/problem=32

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.

The product 7254 is unusual, as the identity, 39 x 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.

Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.

public static LinkedList<string> onetonine = new LinkedList<string>();
static void Main(string[] args)
{
    LinkedList<int> distinct_product = new LinkedList<int>();
    int product = 0;
    for (int a = 1; a < 2000; a++)
    {
        for (int b = 1; b < 2000; b++)
        {
            product = a * b;
 
            if (isDigits(a + "" + b + "" + product))
            {
                if (!distinct_product.Contains(product) )
                    distinct_product.AddLast(product);
            }
        }
    }
    int sum = 0;
    foreach (int prod in distinct_product)
        sum += prod;
    Console.WriteLine("sum : "+sum);
}
 
public static bool isDigits(string s)
{
    onetonine.Clear();
    onetonine.AddLast("1");
    onetonine.AddLast("2");
    onetonine.AddLast("3");
    onetonine.AddLast("4");
    onetonine.AddLast("5");
    onetonine.AddLast("6");
    onetonine.AddLast("7");
    onetonine.AddLast("8");
    onetonine.AddLast("9");
    if (s.Length != 9)
        return false;
    for (int i = 0; i < s.Length; i++)
    {
        if (onetonine.Contains("" + s[i]))
            onetonine.Remove("" + s[i]);
        else
            return false;
    }
    return true;
}

C#: Project Euler Solution to Problem 39

http://projecteuler.net/problem=39

If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120.

{20,48,52}, {24,45,51}, {30,40,50}

For which value of p <= 1000, is the number of solutions maximised?

int Max_P = 0;
int P_position = 0;
for (int p = 1; p < 1000; p++)
{
    int count_p = 0;
    for (int a = 1; a < 500; a++)
    {
        for (int b = 1; b < 500; b++)
        {
            for (int c = 1; c < 500; c++)
            {
                if (  (a + b + c == p) &&
                (Math.Pow(a, 2.00) + Math.Pow(b, 2.00) == Math.Pow(c, 2.00)) )
                    count_p++;
            }
        }
    }
    if (Max_P < count_p)
    {
        Max_P = count_p;
        P_position = p;
    }
}
Console.WriteLine("p = "+P_position);

C#: Project Euler Solution to Problem 47

http://projecteuler.net/problem=47

The first two consecutive numbers to have two distinct prime factors are:

14 = 2 x 7
15 = 3 x 5

Find the first four consecutive integers to have four distinct primes factors. What is the first of these numbers?

static void Main(string[] args)
{
    LinkedList<int> threefactors = new LinkedList<int>();
    int n = 0;
    while (true)
    {
        n++;
        int factcount = 0;
        for (int i = 1; i <= n; i++)
        {
            if (n % i == 0 && isPrime(i))
                factcount++;
        }
        if (factcount == 4)
        {
            threefactors.AddLast(n);
            int lastn = (n - 1);
            int lastn2 = (n - 2);
            int lastn3 = (n - 3);
            if (threefactors.Contains(lastn)  && threefactors.Contains(lastn2) && threefactors.Contains(lastn3))
            {
                Console.WriteLine(n);
                Console.WriteLine(lastn);
                Console.WriteLine(lastn2);
                Console.WriteLine(lastn3);
                break;
            }
        }
    }
}
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;
}