Skip to content

Instantly share code, notes, and snippets.

@haiderktk
Forked from TheRealJAG/path.php
Last active October 1, 2019 02:40
Show Gist options
  • Save haiderktk/37eacaa74d4ab295d0cbcc181b44da18 to your computer and use it in GitHub Desktop.
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.
<?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;
@haiderktk
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment