vendredi 21 février 2014

Re: obj 8-2 topic




Marek Novotny <(E-Mail Removed)> writes:

Some remarks regarding that:

> #!/usr/bin/perl
> # File: obj8-2.pl
> # Use loops and if statements to find the greatest number in the array.
> # Once you determine this number be sure to print it out.
> # Use comments to explain every line of your code:
>
> @array = (42,41,42,31,54,42,56,57,46,58,59,60,34,61);
>
> $a = 0;
> $b = 1;
> $i = 0;
>
> while ($i < ($#array * 2)){
> if (($array[$a]) >= ($array[$b])){
> $c = ($array[$a]);
> $b++;
> }else{
> if (($array[$b]) >= ($array[$a])){


This is the else-part of the original condition. Since
$array[$a] >= $array[$b] was false, $array[$b] > $array[$a]
must be true here and the second if isn't needed.

> $c = ($array[$b]);
> $a++;


Also, it is already known that all elements from @array[$a + 1 .. $b]
are smaller than $array[$b] since $array[$b] is larger than $array[$a]
and all elements in between were <= $array[$a] (the same is true for the
other case). Because of this, the $a++ just ends up as $a = $b, just
calculated in a more expensive way. Taking this into account, a
different algorithm for finding the largest element would be:

$array[$_] > $array[$max] and $max = $_ for 0 .. $#array;

It is initially assumed that $array[$max] is the largest element found
so far. If the element at the current position is larger then that, set
$max = $_ and continue to loop over the array.

The general idea isn't bad once the clutter has been removed.






Aucun commentaire:

Enregistrer un commentaire