Skip to content

Instantly share code, notes, and snippets.

@barakpinchovski
Last active September 9, 2019 11:53
Show Gist options
  • Save barakpinchovski/bb09da54e1fdaa50e14e52452e5991cb to your computer and use it in GitHub Desktop.
Save barakpinchovski/bb09da54e1fdaa50e14e52452e5991cb to your computer and use it in GitHub Desktop.
<?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