Question

Stacks and Java 1. Using Java design and implement a stack on an array. Implement the...

Stacks and Java

1. Using Java design and implement a stack on an array. Implement the following operations: push, pop, top, size, isEmpty. Make sure that your program checks whether the stack is full in the push operation, and whether the stack is empty in the pop operation. None of the built-in classes/methods/functions of Java can be used and must be user implemented.

Practical application

1: Arithmetic operations. (a) Design an algorithm that takes a string, which represents an arithmetic operation, as input and checks whether or not the brackets are correct (balanced) or incorrect (unbalanced). The input string may contain a combination of the following characters: {,},[,],(,),0,1,2,3,4,5,6,7,8,9,+,-,*,/. An obvious hint for this algorithm is to use the stack based solution, and hence you can use the stack implemented in #1. Your algorithm must not check the correctness of the arithmetic operators/operands, but only check for balanced brackets. Your algorithm should also show an error message when the string contains a character that is not one of those listed above. Provide the pseudocode of the algorithm.

(b) Implement the algorithm of (a) in your favorite programming language. Run the program in several cases, including the following (more examples to be asked when the assignment is submitted):

i. (9*[3*{[(3+3)/5]*7}])

iii. ((3*(9-(4*(6-5))))

ii. {3*(2+[3-[4/[6/9]]]})

iv. {2-{3*{6/[[[(((9-0)))]]]}}/7}

(c) Assuming an input string of size n: (i) what is the worst-case time that your algorithm takes to decide whether or not the string is correct (balanced) or incorrect (unbalanced)? (ii) Why? Give your answers in terms of the O-notation.

3. Practical application

2: Context-free language recognizer.

(a) Design an algorithm that recognizes (accepts) strings of the following context-free language: L = {0n 1 n : where n ≥ 1}. That is, strings that contain a number of zeros followed by the same number of ones. Examples of strings in the language are: 01, 0011, 000111, etc. Strings that are not in the language are, for example, 10, 00, 111, 1100, 0101, and many more. The algorithm should take a string of 0’s and 1’s as input and output “Yes” if the string belongs to the language, and “No” if the string doesn’t belong to the language. The algorithm should use a stack. When it reads a 0 from the string, it pushes 0 onto the stack. When it reads a 1, it checks if the stack has a 0, in which case that 0 is popped from the stack. When the stack is empty and the end of the string is reached, the string is recognized as correct (Yes). Otherwise, the string is not in the language (No).

(b) Implement the algorithm of (a) in your favorite programming language and run it on different strings as follows: 01, 000111, 00000001111111, and 10, 00, 00111, 0101, and others.

(c) Assuming an input string of size n: (i) what is the worst-case time that your algorithm takes to decide whether or not the string belongs to the language? (ii) Why? Give your answers in terms of the O-notation. (d) [2 bonus marks] Run your algorithm on strings of lengths n = 2, 4, 8, 16, 32, …, 220 . Compute the running time in nanoseconds and draw a table with the results. Draw a table or a plot of the results for different values of n and compare the results obtained with the complexity you found in (c). Note: if all (or most of) the running times become 0, try running the program 1,000 times and compute the average.

Please include comments so I can understand what the code does and what points. Thank You

0 0
Add a comment Improve this question Transcribed image text
Answer #1

stack.java


public class stack {
    int top=-1;
        char items[] = new char[100];

        void push(char x)
        {
            if (top == 99)
            {
                System.out.println("Stack full");
            }
            else
            {
                items[++top] = x;
            }
        }

        char pop()
        {
            if (top == -1)
            {
                System.out.println("Underflow error");
                return '';
            }
            else
            {
                char element = items[top];
                top--;
                return element;
            }
        }

        boolean isEmpty()
        {
            if (top==-1)
                return true;
            else
                return false;
        }
}

BalanceBrackets.java

import java.util.Scanner;
public class BalancedBrackets {

    static boolean MatchingPair(char character1, char character2)
    {
       if (character1 == '(' && character2 == ')')
         return true;
       else if (character1 == '{' && character2 == '}')
         return true;
       else if (character1 == '[' && character2 == ']')
         return true;
       else
         return false;
    }
    //uses ASCII values to check if character is in range
    static boolean characterOutofRange(char exp[])
            {
                boolean c=true;
               for(int i=0;i<exp.length;i++){
                   int j=exp[i];
                   if((j>=40&&j<=43)||(j==45)||(j>=47&&j<=57)||(j==91)||(j==93)||(j==123)||(j==125))
                       c= true;
                   else{
                       c= false;
                       break;}
               }
               return c;
            }
  
  
    //function to check for balanced brackeks
    static boolean isBalanced(char exp[])
    {
       //declaring an empty stack to push and pop brackets
       stack stk=new stack();
     
       //traversing the given expression
       for(int i=0;i<exp.length;i++)
       {
          
          //if exp[i] is an opening bracket then push it onto stack
          if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
            stk.push(exp[i]);
     
          //if exp[i] is closing bracket, then we try to pop its opening counterpart
          if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
          {
                 
              //if not found
             if (stk.isEmpty())
               {
                   return false;
               }
     
            //if popped opening bracket isn't a counterpart
             else if ( !MatchingPair(stk.pop(), exp[i]) )
               {
                   return false;
               }
          }
          
       }
        
     
       //if stack is empty
       if (stk.isEmpty())
         return true; /*balanced*/
       //if there is an opening bracket left
       else
         {   /*not balanced*/
             return false;
         }
    }
  
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String s;
        System.out.println("Enter expression or -1 to exit");
        s=sc.next();
        while(!(s.equals("-1")))
        {
            char exp[]=s.toCharArray();
            if(characterOutofRange(exp))
            {
                if (isBalanced(exp))
                    System.out.println("Balanced ");
                else
                    System.out.println("Not Balanced ");
            }
            else
                System.out.println("Character out of range! please try again!!");
            System.out.println(" Enter expression or -1 to exit");
            s=sc.next();
        }
    }
  
}

Regardless of what kind of string you enter, whether it's balanced or not, the time complexity of this program will remain O(n)

Add a comment
Know the answer?
Add Answer to:
Stacks and Java 1. Using Java design and implement a stack on an array. Implement the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use Java to implement a basic stack using an array of integers. For the stack, you...

    Use Java to implement a basic stack using an array of integers. For the stack, you will create an array of integers that holds 5 numbers. To make it easier, you can declare the array at the class level. That way you will be able to use the array in any method in your class without using parameters. Your input/output interface should look something like the following: What operation do you want to do? push What number do you want...

  • C++ Include a Stack class but DO NOT use STL stack, do not sumbit code that...

    C++ Include a Stack class but DO NOT use STL stack, do not sumbit code that is similar to www.cplusplus.com/forum/beginner/192479/ Parenthesis Balance Problem Description Compilers require parenthesis, braces, brackets, and angled brackets to be balanced. This means that every time one is opened it must also be close AND everything between the two are also balanced. Balanced: (00) oO100) (C0O Unbalanced: (DI This is easily determined by creating a stack and reading the input. When an open parenthesis is found,...

  • Problem Implement (in C) an algorithm that uses a stack to check if a parentheses sequence is balanced. Note that a par...

    Problem Implement (in C) an algorithm that uses a stack to check if a parentheses sequence is balanced. Note that a parentheses sequence is balanced if it is of the form (S) or of the form (SS), where S is any balanced parentheses sequence. See the courseware for more information on balanced parentheses sequences. Implement a stack using an array Test your program on three different kinds of inputs: 1. String is unbalanced in the sense that there are more...

  • Multiple choice data structures questions about stacks. Here is an INCORRECT pseudocode for the algorithm which...

    Multiple choice data structures questions about stacks. Here is an INCORRECT pseudocode for the algorithm which is supposed to determine whether a sequence of parentheses is balanced: declare a character stack while ( more input is available) { read a character if ( the character is a '(' ) push it on the stack else if ( the character is a ')' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • Please use Java. Write a non-recursive method that uses a stack to check whether its string...

    Please use Java. Write a non-recursive method that uses a stack to check whether its string parameter is a palindrome. Write a program to test and demo your method. Fibonacci Numbers Write a method that uses a stack to determine the desired Fibonacci number. Write a program to test and demo your method. Balancing Grouping Symbols Write a method that takes a string parameter and determines whether the string contains matching grouping symbols. Grouping symbols are parenthesis ( ), curly...

  • tack Assignment Objective: to be familiar with stack operations and applications Requirements: (a) Implement a Java...

    tack Assignment Objective: to be familiar with stack operations and applications Requirements: (a) Implement a Java program that take in an infix expression from the user and output the expression in postfix notation. (b) [15 points bonusl If all the operands in the input are numeric, then your program should evaluate the expression and display its value Hints: deta algorithm for converting an infix expression to the equivalent postf x listed at CSIS ace.edu/n wolf/CS122/infix ostfix.htm

  • need help with balancing brackets in python. I don't really understand it much. an unbalanced one...

    need help with balancing brackets in python. I don't really understand it much. an unbalanced one will look like this: (<x)>(())() For this exercise, you must write a function called balanced brackets brackets in the string, that is: '(' , ') and >', are correctly balanced. This function will be passed a string as an input, and you must check that any parentheses or angled Here are a few examples of strings where brackets are correctly balanced: a (<bcd>ef)g abcde...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert...

    By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert Postfix notation to Infix notation using the following algorithm. In your stack application, you can use only two stacks, one for a stack that can store Postfix notation, and the other is a stack to store infix notation. Also, it would help if you had a function to distinguish between an operation or an operand. Input A B C * + D E /...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT