Look for dates in the digits of Pi in C#

[example]

The example Find patterns within pi in C# looks for patterns within the digits of Pi. You can use that example to look for dates such as 4/1. This example determines whether the first 100 thousand digits of Pi contains a pattern for every date in the year.


When you click the Check button, the following code executes.

// Search for all dates.
private void btnCheck_Click(object sender, EventArgs e)
{
    lstResults.Items.Clear();

    int found = 0;
    int not_found = 0;
    int biggest = -1;
    DateTime date = new DateTime(DateTime.Now.Year, 1, 1);
    DateTime end_date = new DateTime(DateTime.Now.Year, 12, 31);
    while (date <= end_date)
    {
        string pattern = date.Month.ToString() +
            date.Day.ToString();
        int pos = Pi.IndexOf(pattern);
        string short_date = date.Month.ToString() +
            "/" + date.Day.ToString();
        if (pos < 0)
        {
            not_found++;
            lstResults.Items.Add(
                short_date + "\tNot found");
        }
        else
        {
            found++;
            if (biggest < pos) biggest = pos;
            lstResults.Items.Add(
                short_date + "\t" + pos.ToString());
        }

        date = date.AddDays(1);
    }
    lblResults.Text = "Found: " + found.ToString() +
        ", Not found: " + not_found.ToString() +
        ", Biggest position: " + biggest.ToString();
}

This code sets date and end_date to the first and last days of the current year respectively. The code then enters a loop that runs until date is after end_date.

Inside the loop, the program gets the date’s month and day digits. It then searches for those digits within the loaded value of Pi. The code then adds results to the lstResults list box to indicate whether it found the pattern.

The code finishes by displaying the number of date patterns that it found, the number that it didn’t find, and the largest position within the digits of Pi where it found a date pattern. If you look closely at the picture above, you’ll see that the program found every date’s pattern. The pattern that occurred in the largest position was the pattern 1211 for the date 12/11 at position 50,289.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, mathematics, strings and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *