Re: obj 8-2

Discussion in 'Perl Misc' started by Rainer Weikusat, Feb 21, 2014.

  1. Marek Novotny <> 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.
     
    Rainer Weikusat, Feb 21, 2014
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mark Kamoski
    Replies:
    3
    Views:
    15,702
    Jay B. Harlow [MVP - Outlook]
    Aug 9, 2003
  2. Phil Endecott

    Obj* ptr = new Obj(X)

    Phil Endecott, Jun 3, 2005, in forum: C++
    Replies:
    5
    Views:
    464
    Mark P
    Jun 3, 2005
  3. Shalabh Chaturvedi
    Replies:
    2
    Views:
    444
    Mike C. Fletcher
    Feb 20, 2004
  4. Matthew Thorley

    How do you convert a string obj to a file obj?

    Matthew Thorley, May 4, 2005, in forum: Python
    Replies:
    7
    Views:
    503
    Peter Otten
    May 4, 2005
  5. alf
    Replies:
    9
    Views:
    408
Loading...

Share This Page