Last active
August 9, 2021 12:43
-
-
Save elishaukpong/1ac48dcf45cb0ef9448e34484aefdc05 to your computer and use it in GitHub Desktop.
There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
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
//PROBLEM | |
//There is a large pile of socks that must be paired by color. | |
//Given an array of integers representing the color of each sock, | |
//determine how many pairs of socks with matching colors there are. | |
//More details about problem can be found here | |
//https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup | |
function sockMerchant($n, $ar) { | |
// Get the unique version of the array and the count of value appearance. | |
$uniqueArrayAndCount = array_count_values($ar); | |
//initialize the pair count | |
$pairs = 0; | |
//iterate over the unique array | |
foreach ($uniqueArrayAndCount as $key => $sockCount){ | |
//if the count is divisible by 2 then its a pair, | |
//divide it and grab the amount of pairs | |
if($sockCount % 2 == 0){ | |
$pairs += $sockCount / 2; | |
}else{ | |
//if the count is not divisible by 2 then it has a loose pair, | |
//find the remainder after dividing by two and remove it from the sum, | |
// then divide it by 2 and grab the actual amount of pairs. | |
$pairs += ($sockCount - $sockCount % 2) / 2; | |
} | |
} | |
echo $pairs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment