Advertisement
Checosnake

Twitter Challenge Question 2

Jan 20th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 13.18 KB | None | 0 0
  1. ////////////////////////////////////////
  2. //Code Written By: Sergio A. Nuñez    //
  3. //Date of Final Revision: 1/20/2017   //
  4. ///////////////////////////////////////////////////////////////////////////////////////////////
  5. //Summary of Code:                                                                           //
  6. //This program will utilize a modular programming approach to make a rather complex          //
  7. //program simpler. The Driver Program will get input from the system and seperate            //
  8. //it into two seperete deques, one for the expression, and one for the operations.           //
  9. //This program will push character by character to a deque until it encounters a slash, '/'. //
  10. //while parsing it will ignore spaces and call a function to manage the operations           //
  11. //gathered from the input. Once the '/' is encountered it will then push characters          //
  12. //to a different deque that will only store the operations. When there is no more input      //
  13. //The program will then read Operation by operation applying the changes to the expression   //
  14. //deque. 'R' will reverse the string, and 'S' will simplify the expression removing any      //
  15. //redundant parentheses. Once all operations are complete the expression deque will then     //
  16. //be displayed and the next input will be read in, if there is no more input the program     //
  17. //will terminate.                                                                            //
  18. //-------------------------------------------------------------------------------------------//
  19. //Simplify idea:                                                                             //
  20. //Parentheses are only neccessary when you need to break the order of operations             //
  21. //for this reason if there is a variable to the left of the opening parenthesis it will make //
  22. //the parentheses necessary, and if there's only a variable to the right it will make them   //
  23. //redundant and can be taken away. Since in all these inputs there are only multiplication we//
  24. //can assume this rule to simplify the expression.                                           //
  25. ///////////////////////////////////////////////////////////////////////////////////////////////
  26. #include <map>
  27. #include <set>
  28. #include <list>
  29. #include <cmath>
  30. #include <ctime>
  31. #include <deque>
  32. #include <queue>
  33. #include <stack>
  34. #include <string>
  35. #include <bitset>
  36. #include <cstdio>
  37. #include <limits>
  38. #include <vector>
  39. #include <climits>
  40. #include <cstring>
  41. #include <cstdlib>
  42. #include <fstream>
  43. #include <numeric>
  44. #include <sstream>
  45. #include <iostream>
  46. #include <algorithm>
  47. #include <unordered_map>
  48.  
  49. using namespace std;
  50.  
  51. //------------------------------------------------------
  52. //Prototypes for operation functions
  53. //Used for Modular Programming
  54. //------------------------------------------------------
  55. void reverse(deque<char>& str);
  56. void simplify(deque<char>& str);
  57. void Process_Commands(deque<char>& cmd, deque<char>& str);
  58. void dispDeque(deque<char> str);
  59.  
  60. int main() {
  61.     //------------------------------------------------------------------------------
  62.     //Variable Set up
  63.     //------------------------------------------------------------------------------
  64.    
  65.     string input;             //String to handle input
  66.     bool inputover = false;   //Boolean used to determine if theres no more input
  67.                              
  68.     deque<char> str;          //Deques used for easier Stack, and Queue Functionality
  69.     deque<char> cmd;          //*Note: These deques will be used to split input and  *
  70.                               //*differentiate between Expression Tree and operations*
  71.    
  72.     //---------------------------------------------------------------------------
  73.     //This simply makes the program work for Hackerrank's Input Methods
  74.     ///-----------------------------------------------------------------------------
  75.    
  76.     //Cycle until no more input is left
  77.     while(!inputover)
  78.     {
  79.         //Get input and Assign to input string
  80.         getline(cin,input);
  81.        
  82.         //Clear for next input
  83.         cin.clear();
  84.        
  85.         //Check for end of input
  86.         if(input.empty())
  87.         {
  88.             break;  
  89.         }
  90.    
  91.         //===========================================================
  92.         //Implementation Begins Here
  93.         //===========================================================
  94.        
  95.         //Iterate though Input and seperate Expression from Operations
  96.         while(input.length() > 0)
  97.         {
  98.             //If Statement to detect slash to indicate operations
  99.             if(input[0]=='/')
  100.             {
  101.                 input.erase(input.begin());
  102.                 //Iterate through remaining input and add input to Operations Deque
  103.                 while(input.length() > 0)
  104.                 {
  105.                     cmd.push_back(input[0]);
  106.                     input.erase(input.begin());
  107.                 }
  108.             }
  109.             //If statement Used to ignore Spaces
  110.             else if(input[0] == ' ')
  111.             {
  112.                 input.erase(input.begin());
  113.             }
  114.             //Add input, one character at a time, to the Expression Deque
  115.             else
  116.             {
  117.                 str.push_back(input[0]);
  118.                 input.erase(input.begin());
  119.             }
  120.         }
  121.        
  122.         //================================================================================
  123.         //Begin Modular Programming for easier Debugging, Implementation, and Maintenece
  124.         //================================================================================
  125.        
  126.         //Execute Operation Commands
  127.         Process_Commands(cmd,str);
  128.        
  129.         //Display Expression
  130.         dispDeque(str);
  131.        
  132.         //Clear deques for next input
  133.         str.clear();
  134.         cmd.clear();
  135.     }
  136.    
  137.     return 0;
  138. }
  139.  
  140. //Fonction for Reverse Operation
  141. void reverse(deque<char>&str)
  142. {
  143.     //Create Temporary stack
  144.     stack<char> temp;
  145.    
  146.     //Cycle until Expression Deque is empty
  147.     while(!str.empty())
  148.     {
  149.         //In order to maintain readability we
  150.         //want to push in the opposite parentheses
  151.         //since the string is reverse example below
  152.         //
  153.         //Straight Push: (AB)C => C)BA(
  154.         //Reverse Parentheses: (AB)C = > C(BA)
  155.         if(str.front() == '(')
  156.         {
  157.             temp.push(')');
  158.         }
  159.         //Same Reverse Parentheses procedure as before
  160.         else if(str.front() == ')')
  161.         {
  162.             temp.push('(');
  163.         }
  164.         //Push any other character into the stack
  165.         else
  166.         {
  167.             temp.push(str.front());
  168.         }
  169.         //Pop from expression Deque to move on to next
  170.         //character
  171.         str.pop_front();
  172.     }
  173.     //Simultaniously Push contents of stack into expression
  174.     //Deque that will result in a reverse order
  175.     while(!temp.empty())
  176.     {
  177.         str.push_back(temp.top());
  178.         temp.pop();
  179.     }
  180. }
  181.  
  182. //Function for Simplify Operation
  183. void simplify(deque<char>& str)
  184. {
  185.     //------------------------------------------------------------------------------
  186.     //Variable Set up
  187.     //------------------------------------------------------------------------------
  188.     int count = 0;    //Variable used to keep track of parentheses pairs
  189.     int skip = 0;     //Variable used to Group parentheses
  190.     string input;     //String used in parallel with deque to find parentheses pairs
  191.    
  192.     //Check if VERY FIRST ELEMENT is enclosed in parentheses
  193.     if (str[0] == '(')
  194.     {
  195.         //Pass value of expression Deque to string to be manipulated
  196.         for (int i = 0; i < str.size(); i++)
  197.         {
  198.             input += str[i];
  199.         }
  200.         //clear expression deque so simplified output can be pushed in.
  201.         str.clear();
  202.         //Iterate though entire length of string
  203.         for (int i = 0; i < input.length(); i++)
  204.         {
  205.             //Check if current position is an Open parentheses
  206.             if (input[i] == '(')
  207.             {
  208.                 //Once open parentheses is found begin another iterator loop
  209.                 //starting 1 character in front of the open parentheses
  210.                 //to find it's matching closing parentheses
  211.                 for (int j = i + 1; j < input.length(); j++)
  212.                 {
  213.                     //If closing parentheses is found and there are no skips
  214.                     //replace both characters with the count of parentheses groups
  215.                     //and increase count by one
  216.                     if (input[j] == ')' && skip == 0)
  217.                     {
  218.                         input.erase(input.begin() + i);
  219.                         input.insert(i, to_string(count));
  220.                         input.erase(input.begin() + j);
  221.                         input.insert(j, to_string(count));
  222.                         count++;
  223.                         skip = 0;
  224.                         j = input.length();
  225.                     }
  226.                     //if a closed parentheses is found and the skip counter
  227.                     //does not == 0, move on and reduce skip counter by one
  228.                     else if (input[j] == ')' && skip > 0) skip--;
  229.                     //if an open parentheses is encountered increase skip counter
  230.                     //by one, and move on.
  231.                     else if (input[j] == '(') skip++;
  232.                 }
  233.             }
  234.         }
  235.        
  236.         //to compensate for the last parentheses pair increasing count by one
  237.         //reduce it by one to keep the count at the actuall number of parentheses pair
  238.         count--;
  239.        
  240.         //Iterate though expression string to find a number indicating a parentheses
  241.         for (int j = 0; j < input.length(); j++)
  242.         {
  243.             //Check to see if a number is found indicating a parentheses
  244.             if (isdigit(input[j]))
  245.             {
  246.                 //Once the first number indicating a parentheses is found
  247.                 //begin another iterator loop starting 1 character
  248.                 //in front of the number just found to find it's matching
  249.                 //number indicating a closing parentheses
  250.                 for (int k = j + 1; k < input.length(); k++)
  251.                 {
  252.                     //if both numbers match, parentheses pair has been found
  253.                     if (input[k] == input[j])
  254.                     {
  255.                         //==============================================================
  256.                         //Insert Cases to check if Parentheses Redundant or not below
  257.                         //==============================================================
  258.                         //*Could not figure out what was wrong with the last hidden case,
  259.                         //but had the input been revealed tweeks would more than likely
  260.                         //need to go in the code below here*
  261.                         //--------------------------------------------------------------
  262.                        
  263.                         //if there is a variable to the left of an open parentheses
  264.                         //then Order of operations is broken and parentheses are not
  265.                         //redundant, therefore must be kept.
  266.                         //Replace Numbers in string with parentheses character.
  267.                         if (isalpha(input[j - 1]))
  268.                         {
  269.                             input[j] = '(';
  270.                             input[k] = ')';
  271.                            
  272.                         }
  273.                         //Otherwise, since the only operation in the expression tree is
  274.                         //multiplication then parentheses are redundant if there's not a
  275.                         //variable on it's left side, since order of operations will be
  276.                         //respected weather or not the parentheses are there.
  277.                         //erase numbers leaving no parentheses behind.
  278.                         //-------------------------------------------------------------------
  279.                         //*Note that if more operations are going be added to the expression*
  280.                         //*besides multiplication these cases must be changed.              *
  281.                         //-------------------------------------------------------------------
  282.                         else
  283.                         {
  284.                             input.erase(input.begin() + k);
  285.                             input.erase(input.begin() + j);
  286.                             j--;  
  287.                         }
  288.                         //Once closing parentheses has been found and proper action has been
  289.                         //taken, break out of second itterator loop to find another parentheses
  290.                         //pair
  291.                         break;
  292.                     }
  293.                 }
  294.             }
  295.         }
  296.         //iterate though string adding
  297.         //each character to the deque
  298.         for (int i = 0; i < input.length(); i++)
  299.         {
  300.             str.push_back(input[i]);
  301.         }
  302.     }
  303. }
  304.  
  305. //Function to process all Operations
  306. void Process_Commands(deque<char>& cmd, deque<char>& str)
  307. {
  308.     //Itterate through every Operation until none is left.
  309.     while(!cmd.empty())
  310.     {
  311.         //Execute Reverse Operation if R is up next
  312.         if(cmd.front() == 'R')
  313.         {
  314.             reverse(str);
  315.         }
  316.         //Execute Simplify Operation if S is up next
  317.         else if(cmd.front() =='S')
  318.         {
  319.             simplify(str);        
  320.         }
  321.         //Once Command has been processed, or no command
  322.         //is read, pop for next Operation.
  323.         cmd.pop_front();
  324.     }
  325. }
  326.  
  327. //Custom Function to display Deque
  328. void dispDeque(deque<char> str)
  329. {
  330.     for (int i = 0; i < str.size(); i++)
  331.         {
  332.             cout << str[i];
  333.         }
  334.         cout << endl;
  335. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement