CSCI 4230
 Internet Application Development
Fall 2000
 Homework #2

Due Date: September 11, 2000

(1)    Write a small Perl program to read a file of records, process them and print to a report file.  Each record in the file is stored in one line and is a comma separated list of number.  Example:

h2q1dat.txt

1,3,6,7,22,34,45,66,78,90,101,202,12,34,56,77,88,43,33,12,14,17,23,45,66,77
2,4,232,33,33,22,12,23,55,67,88,99,100,80,99,80,80,88,67,79,34,55,66,77,23,23,23,44,44,53,1598,9080

The ouptut file add pair of parenthesis of every group of eleven numbers (or less for the last group) and connect the group by an 'or'.

h2q1out.txt

(1,3,6,7,22,34,45,66,78,90,101) or (202,12,34,56,77,88,43,33,12,14,17) or (23,45,66,77)
(2,4,232,33,33,22,12,23,55,67,88) or (99,100,80,99,80,80,88,67,79,34,55) or (66,77,23,23,23,44,44,53,1598,9080)

A sample session:

>h2q1.pl h2q1dat.txt h2q1out.txt

>type h2q1out.txt
(1,3,6,7,22,34,45,66,78,90,101) or (202,12,34,56,77,88,43,33,12,14,17) or (23,45,66,77)
(2,4,232,33,33,22,12,23,55,67,88) or (99,100,80,99,80,80,88,67,79,34,55) or (66,77,23,23,23,44,44,53
,1598,9080)

>h2q1.pl h2q1dat.txt
Usage: h2q1.pl h2q1dat.txt h2q1out.txt

(2)    Write a Perl function, reverseHash, to accept a hash and return a hash where the roles of keys and values are reversed.  That is the key of the input hash becomes the value of the output hash and vice versa.  If there are more than one keys in the input hash has the same value, they are connected by the symbol '|' in the output hash.  For example, for:

my %in = ("abc", "1", "def", "1", "hij", "2", "kkk", "1", "lmn", "2", "rst", "3");

my %out = reverseHash(%in);
print "Output hash:\n";
foreach my $key (sort keys %out) {
    print "   $key => $out{$key}\n";
}

the printout is:

Output hash:
   1 => kkk|abc|def
   2 => hij|lmn
   3 => rst

(3)    Write a Perl function randomPermutation to accept an array and return an array that is a random permutation.  For example, calling the following function:

sub testRandomPermutation {
    my @list = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    my @result = ();
    my $NUM_TEST = 5;

    print "Input list: ";
    foreach (@list) {
        print "$_ ";
    }
    print "\n\n";

    for (my $i=0; $i<$NUM_TEST; $i++) {
        print "Output list #" . ($i+1) . ": ";
        @result = randomPermutation(@list);
        foreach (@result) {
            print "$_ ";
        }
        print "\n";
    }
}

may output the following:

Input list: 1 2 3 4 5 6 7 8 9 10

Output list #1: 3 5 8 2 10 9 7 4 1 6
Output list #2: 2 10 1 9 5 7 4 3 6 8
Output list #3: 3 9 1 5 10 6 8 2 7 4
Output list #4: 6 9 1 7 3 8 5 4 10 2
Output list #5: 8 4 5 9 2 6 7 10 1 3