Day-of-the-Year Calculation – Solution

The solution for this month’s Exercise involves two steps. The first is to generate a random value from 1 to 365 (inclusive) as a day-of-the-year value. The second is to determine upon which month and day that value falls. That part may offer more difficulty than you anticipate.

To generate the random value, I used this code:

    /* fetch random day of the year */
    srand((unsigned)time(NULL));
    random_day = rand() % 365 + 1;

The rand() function returns an int value. That value is sliced down to 0 through 364 via the % (modulo) operator, then one is added to set the range from 1 to 365.

The second step is to calculate the current month, which requires a few sub-steps.

To reveal on which month a day-of-the-year falls, I created a month[] int array with the day values for 2017:

    int month[12] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

I used a for loop to process the array, accumulating days in variable d. When the value of d is greater than the random_day, the current month is determined and saved in variable m:

    /* calculate month */
    d = 0;
    for(x=0;x<12;x++)
    {
        d += month[x];
        if( d > random_day)
            break;
    }
    m = x;  /* m is the month */

Variable m holds the month value for an array — an element number, used later in the code to display the month name.

At this point, variable d contains the number of days in the months up to and including the day-of-the-year. So the current (element x) month’s number of days must be shaved off:

    d -= month[x];
    day = random_day-d;

The day of the month is calculated from the difference between d and random_day and saved in variable day. The result should result in the day of the month.

Should.

A problem crops up, which I didn’t discover until I ran my solution a few times, when the result of random_day-d is zero. That result occurs on the last day of the month. So the final part of the code tests for the zero condition and, if true, assigns the value day to the number of days in the current month:

    /* deal with last day of the month */
    if( day == 0 )
    {
        m--;
        day = month[m];
    }

Click here to view my entire solution.

Here are some sample runs:


Day 49 of 2017 is February 18

Day 100 of 2017 is April 10

Day 151 of 2017 is May 31

Day 219 of 2017 is August 7

Day 270 of 2017 is September 27

Your solution may differ from mine, but if the results are good, then everything is okee-doke.

Leave a Reply