Re: Big problem : find a number of day.



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.
.



Relevant Pages

  • Re: Bug in &= (bitwise or)
    ... > [Anno again] ... > The bug is still in perl-5.9.2, I've sent a report. ... The bug tracking ticket is #37616, ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)
  • Re: why doesnt sort properly?
    ... >>>I'm willing to bet the DWIM could be achieved by manipulating the ... Double ugh! ... Anno ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)
  • Re: Perl time and Mysql time
    ... Anno. ... I presume unpack() is better. ... A regex, if it's simple like ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)
  • Re: unicode (hebrew) regexp search for new line headaches
    ... > Anno Siegel wrote earlier: ... > When i talked about using ddd and the "inferior perl debugger", ... > slur on the wonderful powerful perl debugger... ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)
  • Re: How to read a perl script from withink itself
    ... This may fail if the script isn't in a normal disk file. ... Anno ... "Reply" at the bottom of the article headers. ...
    (comp.lang.perl.misc)