in reply to Re: help with algorithm
in thread help with algorithm

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?

Replies are listed 'Best First'.
Re: Re: Re: help with algorithm
by sauoq (Abbot) on Nov 17, 2002 at 01:44 UTC

    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.";
    
Re: Re: Re: help with algorithm
by Zaxo (Archbishop) on Nov 17, 2002 at 01:37 UTC

    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