Skip to content

Instantly share code, notes, and snippets.

@mRoca
Created March 25, 2022 11:50
Show Gist options
  • Save mRoca/400b315f6f3519cba2b7bb6ba1e44e65 to your computer and use it in GitHub Desktop.
Save mRoca/400b315f6f3519cba2b7bb6ba1e44e65 to your computer and use it in GitHub Desktop.
<?php
/**
* Usage : php valleys.php 8 DDUUUUDD
*
* 1
*/
function countValleys(string $path): int
{
$res = array_reduce(str_split($path), static function (array $carry, string $step) {
if (!in_array($step, ['U', 'D'], true)) {
throw new \InvalidArgumentException('The step must be U or D');
}
$carry['altitude'] = ($carry['altitude'] ?? 0) + ('U' === $step ? 1 : -1);
$carry['valleys'] = ($carry['valleys'] ?? 0) + ('U' === $step && 0 === $carry['altitude'] ? 1 : 0);
return $carry;
}, []);
return $res['valleys'] ?? 0;
}
$steps = (int)($argv[1] ?? 0);
$path = (string)($argv[2] ?? '');
if (!$steps || $steps !== mb_strlen($path)) {
throw new \InvalidArgumentException('You must provide a valid step & path values');
}
echo countValleys($path);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment