Re: obj 8-2

Discussion in 'Perl Misc' started by George Mpouras, Feb 21, 2014.

  1. how about finding the answer without IF ?


    my @array = qw(42 41 42 31 54 420 56 57 46 58 59 60 34 61);
    my $max = $array[0];
    $max = (($_ + $max)/2) + (abs($_ - $max)/2) foreach @array[1 ..
    $#array];
    print $max
    George Mpouras, Feb 21, 2014
    #1
    1. Advertising

  2. Marek Novotny <> writes:
    > On Fri, 21 Feb 2014 22:36:20 +0200, George Mpouras wrote:
    >
    >> how about finding the answer without IF ?
    >>
    >>
    >> my @array = qw(42 41 42 31 54 420 56 57 46 58 59 60 34 61);
    >> my $max = $array[0];
    >> $max = (($_ + $max)/2) + (abs($_ - $max)/2) foreach @array[1 ..
    >> $#array];
    >> print $max

    >
    > A requirement for the lesson was to use loops and if.
    >
    > Your solution yielded an answer of 420


    Which is correct since a 420 is included in the array. Explanation why
    this works: Let the current value be x and m the largest value found so
    far. A calculation

    (x + m) / 2 + abs(x - m) / 2

    is then performed. There are two different cases here

    1. x < m

    If x < m, then abs(x - m) = m - x hence

    (x + m) / 2 + abs(x - m) / 2
    = (x + m) / 2 + (m - x) / 2
    = (x + m + m - x) / 2
    = m

    2. x >= m

    If x >= m, then abs(x - m) = x - m, hence

    (x + m) / 2 + abs(x - m) / 2
    = (x + m) / 2 + (x - m) / 2
    = (x + m + x - m) / 2
    = x

    While working this out was moderately entertaining, code isn't supposed
    to be worn as a necklace. It is an exectuable description of an
    algorithm intended to solve a particular problem and this description
    ought to be as simple as possible and not as clever as possible to make
    it easy for other people to understand it.
    Rainer Weikusat, Feb 21, 2014
    #2
    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,641
    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:
    449
    Mark P
    Jun 3, 2005
  3. Shalabh Chaturvedi
    Replies:
    2
    Views:
    428
    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:
    484
    Peter Otten
    May 4, 2005
  5. alf
    Replies:
    9
    Views:
    388
Loading...

Share This Page