C/C++, Codes

Code prettifier

So, I came across this interesting problem.Given this : abc{def(ghi)jkl}done. It would print out this.

abc

{

def

(

ghi

)

jkl

}

done.

How do you came about solving it?

This is the extension of the classic problem of matches brackets,parenthesis,curly brackets. If you know how to solve that classic problem, you can solve it. So let’s go back to solving the classic one to pave a way to solve this problem

From ‘Matching bracket’  problem

These must match together: ( ), [ ], { },  order is not limited provided one matches again the other. So : ({})[] is valid, and so is {[]}(), etc

Therefore it would be wise to keep track of those opening brackets(in a list or the like), and whenever reading a close bracket, a comparison with the most recent open bracket(on the list) is fired.

If the comparison failed, it is safe to say that the brackets are not formatted right, and end the program.

I use string as the open-bracket list to reuse its ‘+’ operators.


//matches function

bool matches(char open, char close){

return   ((open == '[' && close == ']')
       || (open == '(' && close == ')')
       || (open == '{' && close == '}'));

}

........

std::string input = "";    //input string-the brackets

std::string stack = "";    //stack starts out empty

.......

//inside loop for each brackets i

if (input[i] == '[' || input[i] == '{' || input[i] == '(')

   stack += input[i];

else if (input[i] == ']' || input[i] == '}' || input[i] == ')'){

   if (!matches(stack[stack.length()-1],input[i]))

      std::cout << "Failed!!!";
   else stack = stack.substr(0,stack.length()-1);

}


To the ‘code-prettifier’ problem
Remember I said this is just the extension of the ‘matching bracket’ problem. The whole idea is the same, you just add detail.

The details here are whatever words before and after the brackets, and the way you print its out. We would read in words until we get to the brackets, which we print words out, print the open bracket out(whenever we encounter one) with the number of spaces equal the number of element on the list of bracket. When we encounter the closing bracket, we print the spaces equal the number of brackets on the list of bracket.

We done.

Full code


#include <iostream>
#include <string>

bool IsWord(char c){
   return (c != '{' && c != '}'
        && c != '[' && c != ']'
        && c != '(' && c != ')');
}

bool matchcbp(char a, char b){
   return ((a =='[' && b == ']')
        || (a == '{' && b == '}')
        || (a == '(' && b == ')'));
}

void printSpace(int n){
   for (int i = 0; i < n; ++i){
      std::cout << " ";
   }
}

int main(){
   std::string input = "abc{xyz(}def";
   std::string stack = "";
   int i = 0;
   std::string word = "";
   while (i < input.length()){
      //other than braces
      if (IsWord(input[i])){
         word += input[i++];
      }
      //can be braces
      else {
         //output the word
         printSpace(stack.length());
         std::cout << word << std::endl;
         word = "";
         //open braces ==> push on stack
         if (input[i] == '[' || input[i] == '{' || input[i] == '('){
            printSpace(stack.length());
            std::cout << input[i] << std::endl;
            stack += input[i];
         }

         //matching braces
         else if (input[i] == ']' || input[i] == '}' || input[i] == ')'){
            if (matchcbp(stack[stack.length()-1],input[i])){
               printSpace(stack.length()-1);
               std::cout << input[i] << std::endl;
               stack = stack.substr(0,stack.length()-1);
            }
            else{
               std::cout << "Not evenly brac" << std::endl;
            }
         }
       i++;
      }
   }
 return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s