Re: Big problem : find a number of day.
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 4 Nov 2005 10:42:42 GMT
Alextophi <ext.astek.brakha@xxxxxxx> wrote in comp.lang.perl.misc:
> *-* I must find for a number '$day' the day or the days of the table
> %day_array:
>
> my $day = 4;
> my %day_array = ("1" => "0", # Dimanche
> "2" => "1", # Lundi
> "4" => "2", # Mardi
> "8" => "3", # Mercredi
> "16" => "4", # Jeudi
> "32" => "5", # Vendredi
> "64" => "6" # Samedi
> );
>
> my $New_day = $day_array{$day}; # result : $New_day = 2
>
>
> *-* problem: how to make if $day = 5 or 11 or another ?
>
> 5 = 4+1 # result 2 et 0
> 11 = 8+2+1 # result 3 et 1 et 0
>
>
> it is a big problem!
There are straightforward bit-shifting solutions to that. Here is one
that involves a little trick:
my $day_mask = 11;
while ( $day_mask ) {
my $next = $day_mask & ( $day_mask - 1);
print "$day_array{ $next ^ $day_mask}\n";
$day_mask = $next;
}
The expression "$day_mask & ( $day_mask - 1)" deletes (sets to zero)
the least significant bit of $day_mask, leaving the other bits unchanged.
So the XOR of both is the least significant bit in isolation, which is
the index into %day_array.
%day_array isn't even strictly necessary, it is nothing but a coarse
table of logarithms (of base 2). So instead of
print "$day_array{ $next ^ $day_mask}\n";
you could also say
print log( $next ^ $day_mask)/log( 2), "\n";
Rounding the quotient would make it more robust.
Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.
- Follow-Ups:
- Re: Big problem : find a number of day.
- From: V S Rawat
- Re: Big problem : find a number of day.
- References:
- Big problem : find a number of day.
- From: Alextophi
- Big problem : find a number of day.
- Prev by Date: Re: just because is a tiger (was: Re: s///x)
- Next by Date: FAQ 4.45 How do I find the first array element for which a condition is true?
- Previous by thread: Re: Big problem : find a number of day.
- Next by thread: Re: Big problem : find a number of day.
- Index(es):
Relevant Pages
|