logo CodeStepByStep logo

stretch

Language/Type: PHP arrays

Write a function named stretch that accepts as a parameter an array of integers, and modifies it to be twice as large, replacing every integer with a pair of integers, each half the original. If a number in the original array is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number.

For example, if an array named $arr stores the values [18, 7, 4, 24, 11], the call of stretch($arr) should change $arr to contain [9, 9, 4, 3, 2, 2, 12, 12, 6, 5] (the number 18 is stretched into the pair 9, 9, the number 7 is stretched into 4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into 12, 12, and 11 is stretched into 6, 5.)

Note: Because PHP integers are number types, dividing two integers which do not divide evenly returns the decimal value of the result instead of an integer (for example, 1 / 2 results in 0.5, not 0). Use intval(a / b) to parse the result into an integer if needed to solve this problem.

A note about references in PHP: In order to write a function passes a parameter as reference (thus modifying its state), you'll need to prepend "&" to the variable declaration in the function header. For example, a function foo that modifies the state of an array parameter may be defined as:

function foo(&$arr) { ... }
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.