in reply to help with algorithm

Think of this in terms of bits, 2 ** $x == 1 << $x. That allows you to decode with bitwise operations. Here's a simple method that uses a hash to translate between names and numbers.

our %daycode = ( Sunday => 1, Monday => 2, Tuesday => 4, Wednesday => 8, Thursday => 16, Friday => 32, Saturday => 64, ); our %codeday; @codeday{ values(%daycode)} = keys %daycode; sub days { my $mask = shift || 127; sort { $daycode($a} <=> $daycode{$b} } grep { $mask & $daycode{$_} } keys %daycode; }
by default, days() returns all the days of the week if no argument is given.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: help with algorithm
by Anonymous Monk on Nov 17, 2002 at 01:15 UTC
    OK, this seems to almost work; I want to make sure I'm using this correctly; I'm trying:
    #!/usr/bin/perl $test = 12; print "Days mask is $test.\n"; our %daycode = ( Sunday => 1, Monday => 2, Tuesday => 4, Wednesday => 8, Thursday => 16, Friday => 32, Saturday => 64, ); our %codeday; @codeday{ values(%daycode)} = keys %daycode; sub days { my $mask = shift || 127; sort { $daycode{$a} <=> $daycode{$b} } grep { $mask & $daycode{$_} } keys %daycode; } @newtest = days($test); foreach $num (@newtest) { print "$newtest[$num]\n"; }
    If I try 1 value for $test, like 4, it accurately returns Tuesday. However, if I use a complex value, like say 12, it returns Tuesday, Tuesday (where it should be Tuesday, Wednesday).

    Am I doing something wrong in interpreting this?

      That code is working fine. You just make an error in the way you check the returned values.

      @newtest = days($test); foreach $num (@newtest) { print "$newtest[$num]\n"; }

      The array, @newtest, is assigned ('Tuesday', 'Wednesday') as expected but you iterate over it and use each element as an index back into @newtest. You are printing $newtest['Tuesday'] and $newtest['Wednesday'] but both 'Tuesday' and 'Wednesday' evaluate to 0 in numerical context. So, You print $newtest[0] twice and $newtest[0] holds 'Tuesday'. That's why you print 'Tuesday' twice.

      Try writing that loop as:

      foreach $day (@newtest) { print $day,"\n"; }
      -sauoq
      "My two cents aren't worth a dime.";
      

      Sub days() returns a list of names of days, just try: print "@newtest",$/; or

      for my $day (@newtest) { print $day, $/; }
      You are indexing with strings which numify to zero, so you get $newtest["Wednesday"] as $newtest[0].

      After Compline,
      Zaxo