Created
May 28, 2021 04:09
-
-
Save kangmasjuqi/d5b605e8c409a68344775299fbf401dc to your computer and use it in GitHub Desktop.
HACKERRANK-TEST-1
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 | |
// HACKERRANK-TEST-1 | |
// | |
// Question : https://imgur.com/aA7JaaA | |
/* | |
* Complete the 'areAlmostEquivalent' function below. | |
* | |
* The function is expected to return a STRING_ARRAY. | |
* The function accepts following parameters: | |
* 1. STRING_ARRAY s | |
* 2. STRING_ARRAY t | |
*/ | |
function calculateFreq($ac){ | |
$freq = array(); | |
foreach($ac as $char){ | |
if(array_key_exists($char, $freq)!==true){ | |
$freq[$char] = 1; | |
}else { | |
$freq[$char] += 1; | |
} | |
} | |
return $freq; | |
} | |
function diffFreq($array_string_1_freq, $array_string_2_freq){ | |
$diff = 0; | |
foreach($array_string_1_freq as $char => $freq){ | |
if(array_key_exists($char, $array_string_2_freq)===true){ | |
$diff = abs($freq - $array_string_2_freq[$char]); | |
if($diff > 3) | |
return 'NO'; | |
} | |
else if($freq > 3){ | |
return 'NO'; | |
} | |
} | |
foreach($array_string_2_freq as $char => $freq){ | |
if(array_key_exists($char, $array_string_1_freq)===true){ | |
$diff = abs($freq - $array_string_1_freq[$char]); | |
if($diff > 3) | |
return 'NO'; | |
} | |
else if($freq > 3){ | |
return 'NO'; | |
} | |
} | |
return 'YES'; | |
} | |
function areAlmostEquivalent($s, $t) { | |
// Write your code here | |
$array_chars = array(); | |
$ii = 0 ; | |
foreach($s as $string){ | |
$array_chars[$ii++]["s"] = str_split($string); | |
} | |
$ii = 0 ; | |
foreach($t as $string){ | |
$array_chars[$ii++]["t"] = str_split($string); | |
} | |
$ii = 0 ; | |
foreach($array_chars as $group_ac){ | |
$array_chars_freq[$ii]["s"] = calculateFreq($group_ac["s"]); | |
$array_chars_freq[$ii]["t"] = calculateFreq($group_ac["t"]); | |
$ii++; | |
} | |
// var_dump($array_chars_freq); | |
$result = array(); | |
foreach($array_chars_freq as $paired_string){ | |
$result[] = diffFreq($paired_string["s"], $paired_string["t"]); | |
} | |
return $result; | |
} | |
$fptr = fopen(getenv("OUTPUT_PATH"), "w"); | |
$s_count = intval(trim(fgets(STDIN))); | |
$s = array(); | |
for ($i = 0; $i < $s_count; $i++) { | |
$s_item = rtrim(fgets(STDIN), "\r\n"); | |
$s[] = $s_item; | |
} | |
$t_count = intval(trim(fgets(STDIN))); | |
$t = array(); | |
for ($i = 0; $i < $t_count; $i++) { | |
$t_item = rtrim(fgets(STDIN), "\r\n"); | |
$t[] = $t_item; | |
} | |
$result = areAlmostEquivalent($s, $t); | |
fwrite($fptr, implode("\n", $result) . "\n"); | |
fclose($fptr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment