In: Computer Science
Using Perl create a program that will output the scores of 3
golfers that are playing nine holes of golf.
Create a blank array, this will be a two-dimensional array
@golf_array;
Load up the follow scores
For hole 1: Golfer 1 shot 4, Golfer 2 shot 3, Golfer 3 shot 5
For hole 2: Golfer 1 shot 3, Golfer 2 shot 3, Golfer 3 shot 4
For hole 3: Golfer 1 shot 7, Golfer 2 shot 5, Golfer 3 shot 5
For hole 4: Golfer 1 shot 6, Golfer 2 shot 3, Golfer 3 shot 4
For hole 5: Golfer 1 shot 3, Golfer 2 shot 7, Golfer 3 shot 4
For hole 6: Golfer 1 shot 3, Golfer 2 shot 3, Golfer 3 shot 3
For hole 7: Golfer 1 shot 4, Golfer 2 shot 4, Golfer 3 shot 5
For hole 8: Golfer 1 shot 5, Golfer 2 shot 5, Golfer 3 shot 4
For hole 9: Golfer 1 shot 3, Golfer 2 shot 6, Golfer 3 shot 3
Print out the scores for each golfer
Golfer 1:
Hole 1 – 4
Hole 2 – 3
…
Hole 9 – 3
Golfer 2:
Hole 1 – 3
Hole 2 – 3
…
Extra credit:
Print out which golfer had the lowest score and what that score
was.
PERL Code:
use warnings;
# Defining and initializing a 2 dimensional array
my @golf_array = (
[ 4, 3, 5],
[ 3, 3, 4],
[ 7, 5, 5],
[ 6, 3, 4],
[ 3, 7, 4],
[ 3, 3, 3],
[ 4, 4, 5],
[ 5, 5, 4],
[ 3, 6, 3],
[ 0, 0, 0] );
print "\n Scores for each golfer :";
for($i = 0; $i < 3; $i++)
{
my @score=0;
print "\n\n Golfer ",$i+1,":\n";
for(my $j =0; $j<9; $j++)
{
print "\n Hole ",$j+1,"-
$golf_array[$j][$i]";
$score += $golf_array[$j][$i];
}
# total score is stored in the last row of the 2D
array of each Golfer
$golf_array[10][$i]=$score;
}
# compute the least score using last row of 2D array
# where the total score of each Golfer is stored
if(($golf_array[10][0] < $golf_array[10][1] ) and
($golf_array[10][0] < $golf_array[10][2])) {
print "\n\n Golfer 1 have least socre : $golf_array[10][0] ";
} elsif( $golf_array[10][1] < $golf_array[10][2] ) {
print "\n\n Golfer 2 have least socre : $golf_array[10][1] ";
} else {
print "\n\n Golfer 3 have least socre : $golf_array[10][2] ";
}
OUTPUT:
Scores for each golfer : Golfer 1: Hole 1- 4 Hole 2- 3 Hole 3- 7 Hole 4- 6 Hole 5- 3 Hole 6- 3 Hole 7- 4 Hole 8- 5 Hole 9- 3 Golfer 2: Hole 1- 3 Hole 2- 3 Hole 3- 5 Hole 4- 3 Hole 5- 7 Hole 6- 3 Hole 7- 4 Hole 8- 5 Hole 9- 6 Golfer 3: Hole 1- 5 Hole 2- 4 Hole 3- 5 Hole 4- 4 Hole 5- 4 Hole 6- 3 Hole 7- 5 Hole 8- 4 Hole 9- 3 Golfer 1 have least socre : 38