-
-
Save haiderktk/37eacaa74d4ab295d0cbcc181b44da18 to your computer and use it in GitHub Desktop.
Write a function that provides change directory (cd) function for an abstract file system.
This file contains hidden or 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 | |
class Path { | |
public $currentPath; | |
function __construct($path) { | |
$this->currentPath = $path; | |
} | |
public function cd($newPath) { | |
$innerCounter = 0; | |
$strOut= ''; | |
$newPath = explode('/',$newPath); | |
$oldPath = explode('/', $this->currentPath); | |
foreach($newPath as $str) { | |
if($str == '..') $innerCounter++; | |
} | |
$oldLength = count($oldPath); | |
for($i=0;$i<($oldLength - $innerCounter);$i++) | |
$strOut .= $oldPath[$i]."/"; | |
$counter = 0; | |
$newLength = count($newPath); | |
for($i=0;$i<$newLength;$i++){ | |
if($newPath[$i] !='..'){ | |
if($newPath[$i] != NULL){ | |
if($counter){ | |
$strOut = $strOut."/".$newPath[$i].''; | |
} else { | |
$strOut = $strOut.$newPath[$i].''; | |
} | |
$counter++; | |
} | |
} | |
} | |
$this->currentPath = $strOut; | |
return $this; | |
} | |
} | |
$path = new Path('/a/b/c/d'); | |
echo $path->cd('../x')->currentPath; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still fails for 3 Three times up: Wrong answer on https://www.testdome.com/questions/php/path/7265?testId=30&testDifficulty=Hard
Example case: Correct answer
Two times down: Correct answer
Three times up: Wrong answer
Complex paths: Correct answer