Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write a function reduce($arr, $func) that takes an array and a function as a

ID: 674780 • Letter: 1

Question

1. Write a function reduce($arr, $func) that takes an array and a function as a parameter. The reduce function should apply the parameter function to each element of the array in succession to produce a single result. Note: the current result should always be the first parameter to the function and the next element of the array should always be the second parameter. You may not use the PHP function array_reduce in your solution. For example, the result of the following should be 10.

function myMax($current, $new) {

return $current < $new ? $new : $current; }

$arr = array(10, 5, 3, 5, 1, 2, 5, 7, 4); print("Max: " . reduce($arr, 'myMax') . "
");

2. Write a function modeMaker() that forms a closure such that the function it returns can be used with your reduce() function above to find the mode of an array. The mode of an array is the value that appears the most frequently (so in the $arr above, the mode is 5). To do this, you will need an array called $seen that keeps the count of times an element has been examined At the end of the reduce function, the $seen array should look like the following for the $arr above: Array ( [10] => 1 [5] => 3 [3] => 1 [1] => 1 [2] => 1 [7] => 1 ) 2 Note that the closure you generate should always be returning the current mode for what it has seen so far (so it will either be the current mode, or the new element passed in). The following is a start for modeMaker:

function modeMaker() {

$seen = array(); return function($current, $new) use (&$seen) {

// your code that uses $seen goes here

}; } $mode = modeMaker();

$arr = array(10, 5, 3, 5, 1, 2, 5, 7, 4);

print("Mode: " . reduce($arr, $mode) . "
");

Explanation / Answer

1. reduce function:

function reduce($arr,f)
{
$curr=$arr[0];
for(int i=1;i<count($arr);i++)
{
$curr=f($curr,$arr[i]);
}

}

2.ModeMaker function:

function modeMaker() {
$seen = array();
return function($current, $new)
use (&$seen) {
// your code that uses $seen goes here
$max=$seen[0];
for(int i=1;i<count($seen);i++)
{
   if($seen[i]>$max)
{
   $max=$seen[i];
   $pos=i;
}
  
}
return $arr[$pos];

};
}
$mode = modeMaker();
$arr = array(10, 5, 3, 5, 1, 2, 5, 7, 4);
print("Mode: " . reduce($arr, $mode) . "
");

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote