develooper Front page | perl.beginners | Postings from April 2002

Re: Quick question on Sorting

Thread Previous
From:
John W. Krahn
Date:
April 29, 2002 11:48
Subject:
Re: Quick question on Sorting
Message ID:
3CCD957B.E3452F83@acm.org
James Poni wrote:
> 
> Hello again (final time)
> 
> I also want to sort the  (number time) field when we have the same day
> eg:
> 
> below:
> ccc gamma sun 3:00
> aaa aplha mon 1:00   <<here the days are sorted as
> eee epsilon mon 3:00  <<as well as the time
> zzz zeta mon 4:00      << is sorted if the same day
> ddd delta tue 1:00  <<
> iii ita tue 1:30    << this is greater
> bbb beta wed 2:00
> 
> How would i modify this program in order to do so ? Do i need a time hash
> eg
> time = (12:00 =>1,12:30=>2,13:00=>3,13:30=>4 ......) ?
> 
> THIS THE PROGRAM
> $line1 = "aaa alpha\nbbb beta\nccc gamma\nddd  delta\neee epsilon\nzzz
> zeta\niiii ita\n";
> $line2 = "mon\nwed\nsun\ntue\nmon\nmon\ntue\n";
> $line3 = "1:00\n2:00\n3:00\n1:00\n3:00\n4:00\n1:30\n";
> 
> open ( ALPH, ">pl.txt" ) || die "Cant open\n";
> print ALPH $line1;
> close ALPH;
> open (AP, "<pl.txt" )  || die "Cant open\n";
> $info1 = <AP>;
> close AP;
> 
> open ( DAY, ">da.txt" ) || die "Cant open\n";
> print DAY $line2;
> close DAY;
> open (DA, "<da.txt" )  || die "Cant open\n";
> @info2 = <DA>;
> close DA;
> 
> open ( NUM, ">numb.txt" ) || die "Cant open\n";
> print NUM $line3;
> close NUM;
> open ( NU, "<numb.txt" ) || die "Cant open\n";
> @info3 = <NU>;
> close NU;
> 
> my @info;
> my %days = (
>    sun => 0,
>    mon => 1,
>    tue => 2,
>    wed => 3,
>    thu => 4,
>    fri => 5,
>    sat => 6,
>    );
> 
> my $count;
> chomp, push @{$info[$count++]}, $_ for @info1;
> $count = 0;
> chomp, push @{$info[$count++]}, $_ for @info2;
> $count = 0;
> chomp, push @{$info[$count++]}, $_ for @info3;
> 
> @info = sort { $days{$a->[1]} <=> $days{$b->[1]}  } @info;
> 
> for my $row ( @info ) {
>   print "@$row\n";
> }
> 
> I think i need another sort for time here but im not entirely sure how this
> sort above sort works?


my $count;
chomp, push @{$info[$count++]}, $_ for @info1;
$count = 0;
chomp, push @{$info[$count++]}, $_ for @info2;
$count = 0;
chomp, push @{$info[$count++]}, sprintf '%02d:%02d', split /:/ for @info3;

@info = sort { $days{$a->[1]} <=> $days{$b->[1]} || $a->[2] cmp $b->[2] } @info;

for my $row ( @info ) {
    print "@$row\n";
    }


John
-- 
use Perl;
program
fulfillment

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About