Last active
September 9, 2019 11:53
-
-
Save barakpinchovski/bb09da54e1fdaa50e14e52452e5991cb to your computer and use it in GitHub Desktop.
PHP solution for https://www.hackerrank.com/challenges/sock-merchant/
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 | |
$exampleArray = [9, 10 , 20 , 20 ,10 ,10 ,30 ,50 ,10 ,20]; | |
$len = count($exampleArray); | |
echo sockMerchant($len, $exampleArray); | |
// Assumptions for sockMerchant function: | |
// 1. $n is the actual size of $ar (derived from count($ar)) | |
// 2. $ar values are: | |
// 2.a. Valid ( 1 <= a[i] <= 100 ) | |
// 2.b. Integers ( gettype(a[i]) === 'integer' ) | i: 0 to $n | |
function sockMerchant($n, $ar) { | |
if (gettype($n) !== 'integer' || !$n) { | |
return 0; | |
} | |
function getPairs($carry, $socks) { | |
return $carry += floor($socks / 2); | |
} | |
$matchingSocks = array_count_values($ar); | |
return array_reduce($matchingSocks, "getPairs"); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment