Re: obj 8-2

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

1. George MpourasGuest

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

2. Rainer WeikusatGuest

Marek Novotny <> writes:
> On Fri, 21 Feb 2014 22:36:20 +0200, George Mpouras wrote:
>
>>
>>
>> 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.
>

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