Sales by Match

HackerRank 問題: Sales by Match

Question

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.

HackerRank 問題: Sales by Match

Answer

<?php

/*
 * Complete the 'sockMerchant' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER n
 *  2. INTEGER_ARRAY ar
 */

function sockMerchant($number_of_socks, $socks_color_list) {
    $socks_color_mapping = [];

    // count each socks color
    foreach ($socks_color_list as $socks_color) {
        if (!isset($socks_color_mapping[$socks_color])) {
            $socks_color_mapping[$socks_color] = 1;
            continue;
        }
        $socks_color_mapping[$socks_color]++;
    }

    // find pair of socks
    $all_pair_of_socks_number = 0;
    foreach ($socks_color_mapping as $socks_number) {
        $pair_of_socks = (int) floor($socks_number / 2);
        $all_pair_of_socks_number += $pair_of_socks;
    }

    return $all_pair_of_socks_number;
}

$fptr = fopen(getenv("OUTPUT_PATH"), "w");

$n = intval(trim(fgets(STDIN)));

$ar_temp = rtrim(fgets(STDIN));

$ar = array_map('intval', preg_split('/ /', $ar_temp, -1, PREG_SPLIT_NO_EMPTY));

$result = sockMerchant($n, $ar);

fwrite($fptr, $result . "\n");

fclose($fptr);

Reference