Problem of The Day 2 January — Nikhil and Commands
Published in
2 min readJan 2, 2017
Nikhil and Commands
Nikhil learnt two new commands pwd and cd on the first day of Operating Systems lab.
pwd — command displays the current working directory and,
cd — changes the location of working directory.
If the cd parameter contains “..”(without quotes), that means to step one directory back.
The absolute path of directory is separated by slashes “/”(without quotes).
The default root directory is “/”.
Your task is to print the current working directory.
Input
Input description.
- The first line of input contains T, denoting the number of test cases.
- The second line of input contains N, denoting the number of commands.
- Then N lines follow, each containing either a cd command or pwd command.
Output
Output description.
- For each pwd command, output the absolute path of current directory.
Constraints
Should contain all the constraints on the input data that you may have. Format it like:
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 100
- Maximum length of cd parameter ≤ 200
Example
Input:
1
9
pwd
cd /home/csed
pwd
cd /lab/root/../dir
pwd
cd /home
pwd
cd lab
pwdOutput:
/
/home/csed/
/lab/dir/
/home/
/home/lab/ExplanationSelf - Explanatory.Problem Link: Nikhil and CommandsSolution will be posted tomorrow.SOLUTIONIn this problem, we will take a vector and store the given path by splitting by "/ "
we push the each substring between two "/" and if any substring arrive is ".." then we delete the last push element.
Then there are different cases which we have to handle are if cd /(any substring)
then we have to clear the previously stored path and then again process the string.
One case will be cd (any substring) then we don't have to clear the previously stored path push the rest of the path again.
For pushing and deleting purpose we will use vector.
Code will make the approach clear.
CODE
#include<iostream>
#include<vector>
using namespace std;int main()
{
vector v; //VECTOR TO STORE THE STRINGS AFTER SPLITTING
vector::iterator it; //ITERATOR TO REACH AT THE END IF ".." APPEARint T; cin>>T;string command,path;while(T--) {
int N; cin>>N;
v.clear(); //CLEARING VECTOR AT EACH NEW Nfor(int i=1;i<=N;i++) {
cin>>command;//IF COMMAND IS PWD THEN WE ITERATE THROUGH THE VECTOR AND APPEND IT WITH THE ANSWER
if(command == "pwd") {
int sz = v.size();
string ans="/";
for(int j=0;j<sz;j++)
{
ans = ans +v[j] + '/';
}
cout<<ans<<endl;
}
else {
cin>>path;
//FOR CASE cd /temp/dir/../lab
if(path[0] =='/')
{
//CLEARING VECTOR AS NEW DIRECTORY WILL BE OPEN
v.clear();
path = path.substr(1,path.length());
}//SPLITING LOGIC
for(int j=0;j<path.length();j++)
{
string temp="";
while(j<path.length() && path[j]!='/') {
temp+=path[j]; j++;
}
//IF STRING BETWEEN ANY TWO SLASHES IS .. THEN JUST DELELTE THE PREVIOUS DIRECTORY
if(v.size()>0 && temp =="..")
{
it = v.end();
it--;
v.erase(it);
}
else
v.push_back(temp); //PUSH IF ITS NOT ..
}
}
}}
}