in reply to How Many Mondays in Date Range?

This seems to be a little better, benchmarkwise (it assumes days are numbered 0-6):
use strict; # Days start at 0, just like arrays my $start_day = 6; my $days = 7; my @cnts = daycounts($start_day, $days); for (0..6) { print "$_: $cnts[$_]\n"; } sub daycounts { use integer; my $start_day = shift; my $days = shift; my $end_day = ($start_day + $days) % 7; my $compare = ($start_day <= $end_day) ? sub { my $num = shift; $start_day <= $num and $num <= $end_day } : sub { my $num = shift; $num <= $end_day or $start_day <= $num }; my @adjust = map { $compare->($_)? 1 : 0 } 0..6; my $cnts = $days / 7; map { $cnts + $adjust[$_] } 0..6; }
Update: There. fixed. Except now its slower :( though if you unroll that sub reference/dereference and map into two separate maps then its faster :)

Another update: Re:ThuG's reply - I made the assumption that zero days means just the start day, and 1 day means the start day and the next day, so 17 days from Wednesday would take you to Saturday, not Friday. So just subtract one from $days coming in to get what you expect.

Replies are listed 'Best First'.
Runrig's Solution RE: How Many Mondays in Date Range?
by THuG (Beadle) on Aug 02, 2001 at 18:13 UTC

    I'm using 1..7 because Date::Manip returns 1 for the first day of the week, not 0. Yes, I loose the 0 index. That isn't a problem since I can very easily add or subtract 1 as needed to convert between Date::Manip and this code.

    When I step through your code, which by the way, took some work for me since you are using much Perl mojo that I'm just not used to using, I am not getting the answer I expect.

    If you start on Wednesday ($start_day = 2) and run to the third Friday ($days = 17), then you should have two Mondays, Tuesdays, Saturdays, and Sundays, and three Wednesdays, Thrusdays, and Fridays. I expect 2, 2, 3, 3, 3, 2, 2, but I get 2, 2, 3, 3, 3, 3, 2.

    -Travis