Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: day of year calculation

by mlh2003 (Scribe)
on Feb 22, 2005 at 13:52 UTC ( #433330=note: print w/ replies, xml ) Need Help??


in reply to day of year calculation

One way to speed things up a little is to get rid of the for loop by replacing the array containing the number of days in each month with the cumulative number of days. If the year is a leap year, add 1 to the result if the month is >2.

UPDATE (for explanation): In the code I check for the month > 1 since I subtract 1 from the month in the previous line.

#!/usr/local/bin/perl use strict; sub dayofyear { my ($day1,$month,$year)=@_; my @cumul_d_in_m=(0,31,59,90,120,151,181,212,243,273,304,334,365); my $doy=$cumul_d_in_m[--$month]+$day1; $doy++ if (&leap($year) && $month>1); return $doy; } sub leap { my $y = shift; return 0 unless $y % 4 == 0; return 1 unless $y % 100 == 0; return 0 unless $y % 400 == 0; return 1; } print dayofyear(10,3,2005)."\n"; print dayofyear(10,3,2004)."\n"; print dayofyear(10,2,2005)."\n"; print dayofyear(10,2,2004)."\n";
This gives the following output:
69
70
41
41


Comment on Re: day of year calculation
Download Code
Re^2: day of year calculation
by fglock (Vicar) on Feb 22, 2005 at 14:53 UTC

    1 less function call:

    #!/usr/local/bin/perl use strict; sub dayofyear { my ($day1,$month,$year)=@_; my @cumul_d_in_m = (0,31,59,90,120,151,181,212,243,273,304,334,365); my $doy=$cumul_d_in_m[--$month]+$day1; return $doy if $month < 2; return $doy unless $year % 4 == 0; return ++$doy unless $year % 100 == 0; return $doy unless $year % 400 == 0; return ++$doy; } print dayofyear(10,3,2005)."\n"; print dayofyear(10,3,2004)."\n"; print dayofyear(10,2,2005)."\n"; print dayofyear(10,2,2004)."\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://433330]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (10)
As of 2014-09-23 15:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (224 votes), past polls