L
L
littleguga2015-12-07 16:06:13
Programming
littleguga, 2015-12-07 16:06:13

How to find max value without ?/switch/if?

So far, only the solution with cycles has come to mind.
Here is an example:

$arr = [1,2,3,4,5,6,98,65,190];
$max = $arr[0];
foreach($arr as $val){
     while($val > $max){
          $max = $val;
           break;
     }
}

Maybe there are more beautiful solutions?
upd:
Not tied to the language. PHP, just as an example. Interested in the algorithm itself.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Movchan, 2015-12-07
@littleguga

You can write a function maxwithout using conditional statements:

def max_(a, b):
    return (a + b + abs(a-b)) / 2;

m = 0
arr = [1, 2, 3, 4, 5, 6, 98, 65, 190]
for val in arr:
    m = max_(m, val)

print(m)

F
FoxInSox, 2015-12-07
@FoxInSox

What else algorithm? Branch operations are a basic element of a programming language. Your question implied the default use of the branch operator. And in the case you mentioned, while is just a special case of if.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question