Created
October 18, 2022 12:07
-
-
Save noriel0010/e64880ddfeee1f7483002a55d6fd36fe to your computer and use it in GitHub Desktop.
A simple code to count valley, hackerrank.com sample exercise using php
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 | |
function countingValleys($steps, $path) { | |
// Write your code here | |
if(strlen($path)!==($steps)){ | |
return false; | |
} | |
$sea_level = 0; | |
$valley = 0; | |
$mountain = 0; | |
foreach(str_split($path) as $p){ | |
if('U' === strtoupper($p)){ | |
$sea_level++; | |
if($sea_level===0){ | |
$valley++; | |
} | |
} | |
if('D' === strtoupper($p)){ | |
$sea_level--; | |
if($sea_level===0){ | |
$mountain++; | |
} | |
} | |
} | |
// return number of valley, change to mountain if you want to count mountains | |
return $valley; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment