Skip to content

Instantly share code, notes, and snippets.

@noriel0010
Created October 18, 2022 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noriel0010/e64880ddfeee1f7483002a55d6fd36fe to your computer and use it in GitHub Desktop.
Save noriel0010/e64880ddfeee1f7483002a55d6fd36fe to your computer and use it in GitHub Desktop.
A simple code to count valley, hackerrank.com sample exercise using php
<?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