Created
March 6, 2023 18:17
-
-
Save djamol/db6df6b31ff755da27d244d0c87137d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17. | |
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array. | |
Examples | |
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"] | |
Output: 7-4-6-10-6 | |
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"] | |
Output: 3-3-6-2 | |
*/ | |
function ArrayChallenge($strArr) { | |
$arr1= explode(',',trim($strArr[0],'[]')); | |
$arr2= explode(',',trim($strArr[1],'[]')); | |
$arr1=array_map('intval',$arr1); | |
$arr2=array_map('intval',$arr2); | |
if(count($arr1) != count($arr2)){ | |
$n=max(count($arr1),count($arr2)); | |
$arr1=array_pad($arr1,$n,0); | |
$arr2=array_pad($arr2,$n,0); | |
} | |
$out = array_map(function ($a,$b){ | |
return (string)($a+$b); | |
},$arr1,$arr2); | |
return implode('-',$out); | |
} | |
// keep this function call here | |
echo ArrayChallenge(fgets(fopen('php://stdin', 'r'))); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment