Reputation: 863
You are given an array in PHP, which contains positive integers and/or recursively nested arrays of positive integers. It may, for example, be initialized as:
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
Write a function "function MaxArray($arr)" which returns the maximum value contained in $arr or some array nested within $arr. In the example, the returned value should be 404.
function MaxArray($arr){
static $x = 0;
foreach($arr as $array){
if(is_array($array)) $x = MaxArray($array);
else if($array > $x) $x = $array;
}
return $x;
}
//additional output just for testing
$arr = array(array(141,5651,161), 2, 45446, array(101, 202, array(303,4)));
//additional output just for testing
print MaxArray($arr);
It works every time I run it but the online code generator would not accept. Is this an error on there part or is it me...?
Also on a personal note I would like to say thank you to everyone on stackoverflow, such an amazing site. Four years ago I knew nothing about programming and now I have built this from scratch audio visual reviews and I am writing android apps in java!
Update: This question was taken from an online test that I sat. No error information was displayed, however the code generator just gave the response of wrong answer. Thus, I was not marked for the question.
I wanted to check my solution before appealing the decision.
Upvotes: 0
Views: 483
Reputation: 120
<?php
$arr = [[141, 151, 161], 2, 3, [101, 202, [303, 404]]]
/**
* @param $input
* @return int
*/
function getActMax($input)
{
if ( ! is_array($input))
{
return $input;
} else
{
return findMax($input);
}
}
/**
* @param array $inputs
* @return int
*/
function findMax(array $inputs)
{
//Maybe the first item in the list is the biggest, this is our current max value
$max = getActMax(current($inputs));
foreach ($inputs as $v)
{
//If we found a bigger, change our max value
if (getActMax($v) > $max)
{
$max = getActMax($v);
}
}
return (int)$max;
}
var_dump(findMax($arr));
Upvotes: 0
Reputation: 86535
# so... this works well enough
$arr = array(array(141,5651,161), 2, 45446, array(101, 202, array(303,4)));
print MaxArray($arr); // outputs 45446
print "\n";
# but now...let's try it again. In the same script. *gasp!*
$arr2 = array(42);
print MaxArray($arr2); // outputs 45446 (!!!)
The problem is that static variable; it isn't getting cleared between calls to the function. So previous results affect future ones. This is almost certainly incorrect, and would certainly cause a knowledgeable human judge to reject your code.
Get rid of the static variable. You can pass it as an argument, you can simply compare with subresults like the other answer here was suggesting... or you could show off with a closure and array_walk_recursive
. :)
function MaxArray($arr) {
$max = -1;
array_walk_recursive($arr, function($x) use (&$max) {
if ($x > $max) $max = $x;
});
return $max;
}
Upvotes: 1