Skip to content

Instantly share code, notes, and snippets.

@handrihmw
Last active October 7, 2020 05:36
Show Gist options
  • Save handrihmw/69b7d4673611f581b658c890d3a16bf0 to your computer and use it in GitHub Desktop.
Save handrihmw/69b7d4673611f581b658c890d3a16bf0 to your computer and use it in GitHub Desktop.
Hacker Rank Challenge
<-- Sock Merchant Start -->
<?php
function sockMerchant($n, $ar) {
return array_sum(array_map(function ($n) {
return intval($n / 2);
}, array_count_values($ar)));
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%d\n", $n);
fscanf($stdin, "%[^\n]", $ar_temp);
$ar = array_map('intval', preg_split('/ /', $ar_temp, -1, PREG_SPLIT_NO_EMPTY));
$result = sockMerchant($n, $ar);
fwrite($fptr, $result . "\n");
fclose($stdin);
fclose($fptr);
?>
<-- Sock Merchant End -->
<-- Counting Valleys Start -->
<?php
function countingValleys($n, $s) {
$count = $seaLevel = 0;
for ($i = 0; $i < $n; $i++) {
if ($s[$i] === 'U') {
++$seaLevel;
if ($seaLevel === 0) {
++$count;
}
} else {
--$seaLevel;
}
}
return $count;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%d\n", $n);
$s = '';
fscanf($stdin, "%[^\n]", $s);
$result = countingValleys($n, $s);
fwrite($fptr, $result . "\n");
fclose($stdin);
fclose($fptr);
?>
<-- Counting Valleys End -->
<-- Jumping on The Clouds Start -->
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
$c_temp = fgets($handle);
$c = explode(" ",$c_temp);
array_walk($c,'intval');
$res = 0;
for ($i = 0; $i < ($n-1);) {
if ($c[$i+2] == 1) {
$res++; $i++;
} else { $res++; $i+=2; }
}
echo $res."\n";
?>
<-- Jumping on The Clouds End -->
<-- Repeated Start -->
<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%s",$s);
fscanf($handle,"%ld",$n); $cnt = 0;
for ($i = 0;$i<strlen($s);$i++) if ($s[$i] == 'a') $cnt++;
$p = floor($n / strlen($s));
$p *= $cnt;
if ($n%strlen($s)) {
$r = $n % strlen($s);
for ($i = 0; $i < $r; $i++) if ($s[$i] == 'a') $p++;
}
echo $p;
?>
<-- Repeated End -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment