That'll give you O(log2 n) queries, but there's a simple way to get to O(1). I had it mostly coded up when you posted. The code is nearly identical to yours (sick minds think alike?), so I'll provide the delta.
When reading the first datafile and preparing the data structure, instead of using a hash, use an array.
The probe them becomesfor ( date2offset($start) .. date2offset($end) ) { push @{$effective[$_]}, \$data; }
I'll leave date2offset() as an exercise, other than noting that there's a non-obvious trick you can pull with it. Instead of a 1-to-1 mapping, you can do something not-quite right, likemy $results = $effective[date2offset($date)]; # O(1) if ( defined($results) { # @$results is an array of all matching $data }
This is a classic time-for-space tradeoff, simplifying the calculation by assuming all months are 31 days long, resulting in 6-7 bogus offsets per year. Note that it has no effect on probe time.sub date2offset { my($yyyymmdd) = @_; my $year = int($yyyymmdd/ 10000) - 1970; my $mmdd = $yyyymmdd % 10000; my $month = int($mmmdd / 100) - 1; my $day = $mmdd % 100 - 1; return $year * (12 * 31) + $month * 31 + $day; }
In reply to Re: Re: Code efficiency / algorithm - O(1)
by dws
in thread Code efficiency / algorithm
by dave8775
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |