SHARE
TWEET

Untitled

a guest Sep 20th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. $examplePath = 'DDUUUUDD';
  3. $len = strlen($examplePath);
  4.    
  5. echo countingValleys($len, $examplePath);
  6.  
  7. // Assumptions for countingValleys function:
  8. // 1. $n:
  9. //     1.a. Represents the number of steps that were taken
  10. //     1.b. Is the actual length of $s (derived from strlen($s))
  11. //     1.c. Range is between: 2 <= n <= pow(10,6)
  12. // 2. $s values are:
  13. //     2.a. Represents uphills ('U') and downhills ('D')
  14. //     2.b. Valid ( 'D' === strtoupper(a[i]) || 'U' === strtoupper(a[i]) )
  15. //     2.c. Strings ( gettype(a[i]) === 'string' ) | i: 0 to $n
  16.  
  17. // Returns number of valleys in $s
  18. function countingValleys($n, $s) {
  19.     $valleys = $altitude = 0; // Default value
  20.    
  21.     if (gettype($n) !== 'integer' || !$n || $n % 2 || gettype($s) !== 'string') {
  22.         return $valleys; // Return default function value
  23.     }
  24.    
  25.     $s = strtolower($s); // Turn 'DDUU...' into 'dduu...'
  26.    
  27.     for ($i = 0; $i < $n; $i++) {
  28.         $step = $s[$i];
  29.         if ($altitude === -1 && $step === 'u') {
  30.             $valleys++;
  31.         }
  32.         $altitude += -1 * ($step === 'd') + 1 * ($step === 'u');
  33.     }
  34.    
  35.     return $valleys;
  36. }
  37. ?>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top