Wednesday, August 18, 2010

Given a file, print the count of all the words (OUTPUT: word --> count)

This is using two for loops so the time complexity would be n^2, where n is the no of lines in file1.



#!/depot/perl-5.8.3/bin/perl

open FH1, "file1" or die "Cannot open file file1 : $!";
@array=<FH1>;
foreach $l (@array) {
push(@arr1,split(/\s+/,$l));
}
my %hash1;
foreach $y (@arr1) {
$hash1{$w}=0;
foreach $z (@arr1) {
if ($y eq $z) {
$hash1{$y}++;
}
}
}

foreach $key (keys %hash1) {
print "$key --> $hash1{$key} \n";
}



This is using a while and a for loop, the time complexity is "n":

#!/usr/local/bin/perl

use strict;
use warnings;

my %count;
my $file = shift or die "Usage: $0 FILE\n";
open my $fh, '<', $file or die "Could not open '$file' $!";
while (my $line = <$fh>) {
        chomp $line;
        foreach my $str (split /\s+/, $line) {
             $count{$str}++;
        }
}

foreach my $str (sort keys %count) {
        printf "%-31s %s\n", $str, $count{$str};
}


USAGE: ./count.pl  txt1

OUTPUT:

Hii                             2
am                              1
are                             3
doing                           1
hii                             2
how                             2
well                            1
you                             3

No comments:

Post a Comment