Question

In: Computer Science

What java program would you write to solve the following problems and why does it work?...

What java program would you write to solve the following problems and why does it work? Please also comment on other students’ code at least three times. 1) Implement MyArrayStack (constructor, push, pop, peek and isEmpty), and MyLinkedQueue with both next and previous pointers (constructor, enqueuer/offer, dequeuer/poll, peek and isEmpty), and write the following two program to test them. You must use MyArrayList or MyLinkedList for the implementation. 2) For stack testing, write a program to check if a string has matching parenthesis such as “(())”, but not “)(“. 3) For stack testing, use it to “Evaluating Expressions” using the algorithm given in the class.

What java program would you write to solve the following problems and why does it work? Please also comment on other students’ code at least three times. 1) Add support for exponent ~ for the problem in the previous question. 2) An animal shelter, which holds only dogs and cats, operates on a strictly "first in, first out" basis. People must adopt either the "oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the myLinkedlist data structure you created in previous discussion question. 3) You have an integer and you can flip exactly one bit from a O to a 1. Write code to find the length of the longest sequence of 1 s you could create. EXAMPLE Input: 1775 (or: 11011101111) Output: 8.

Solutions

Expert Solution

ANSWER:

SOURCE CODE:



/**

* Stack implementation

*/

public class MyArrayStack<T> {

private int stackSize;

private T[] stackArr;

private int top;

/**

* constructor to create stack with size

* @param size

*/

public MyArrayStack(int size) {

this.stackSize = size;

this.stackArr = (T[]) new Object[stackSize];

this.top = -1;

}

/**

* This method adds new entry to the top

* of the stack

* @param entry

* @throws Exception

*/

public void push(T entry){

if(this.full()){

System.out.println(("Stack is full. Increasing the capacity."));

}

// System.out.println("Adding: "+entry);

this.stackArr[++top] = entry;

}

/**

* This method removes an entry from the

* top of the stack.

* @return

* @throws Exception

*/

public T pop() throws Exception {

if(this.empty()){

throw new Exception("Stack is empty. Can not remove element.");

}

T entry = this.stackArr[top--];

// System.out.println("Removed entry: "+entry);

return entry;

}

/**

* This method returns top of the stack

* without removing it.

* @return

*/

public T peek() {

return stackArr[top];

}

/**

* This method returns true if the stack is

* empty

* @return

*/

public boolean empty() {

return (top == -1);

}

/**

* This method returns true if the stack is full

* @return

*/

public boolean full() {

return (top == stackSize - 1);

}

}

############ Evaluate #######

public class Evaluate {

public static int evaluate(String expression) throws Exception

{

char[] tokens = expression.toCharArray();

// Stack for numbers: 'values'

MyArrayStack<Integer> values = new MyArrayStack<Integer>(100);

// Stack for Operators: 'ops'

MyArrayStack<Character> ops = new MyArrayStack<Character>(100);

for (int i = 0; i < tokens.length; i++)

{

// Current token is a whitespace, skip it

if (tokens[i] == ' ')

continue;

// Current token is a number, push it to stack for numbers

if (tokens[i] >= '0' && tokens[i] <= '9')

{

StringBuffer sbuf = new StringBuffer();

// There may be more than one digits in number

while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')

sbuf.append(tokens[i++]);

values.push(Integer.parseInt(sbuf.toString()));

}

// Current token is an opening brace, push it to 'ops'

else if (tokens[i] == '(')

ops.push(tokens[i]);

// Closing brace encountered, solve entire brace

else if (tokens[i] == ')')

{

while (ops.peek() != '(')

values.push(applyOp(ops.pop(), values.pop(), values.pop()));

ops.pop();

}

// Current token is an operator.

else if (tokens[i] == '+' || tokens[i] == '-' ||

tokens[i] == '*' || tokens[i] == '/')

{

// While top of 'ops' has same or greater precedence to current

// token, which is an operator. Apply operator on top of 'ops'

// to top two elements in values stack

while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))

values.push(applyOp(ops.pop(), values.pop(), values.pop()));

// Push current token to 'ops'.

ops.push(tokens[i]);

}

}

// Entire expression has been parsed at this point, apply remaining

// ops to remaining values

while (!ops.empty())

values.push(applyOp(ops.pop(), values.pop(), values.pop()));

// Top of 'values' contains result, return it

return values.pop();

}

// Returns true if 'op2' has higher or same precedence as 'op1',

// otherwise returns false.

public static boolean hasPrecedence(char op1, char op2)

{

if (op2 == '(' || op2 == ')')

return false;

if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))

return false;

else

return true;

}

// A utility method to apply an operator 'op' on operands 'a'

// and 'b'. Return the result.

public static int applyOp(char op, int b, int a)

{

switch (op)

{

case '+':

return a + b;

case '-':

return a - b;

case '*':

return a * b;

case '/':

if (b == 0)

throw new

UnsupportedOperationException("Cannot divide by zero");

return a / b;

}

return 0;

}

// Driver method to test above methods

public static void main(String[] args) throws Exception

{

System.out.println(evaluate("10 + 2 * 6"));

System.out.println(evaluate("100 * 2 + 12"));

System.out.println(evaluate("100 * ( 2 + 12 )"));

System.out.println(evaluate("100 * ( 2 + 12 ) / 14"));

}

}

Related Solutions

Write a program in java processing. Write a program that does the following: · Assume the...
Write a program in java processing. Write a program that does the following: · Assume the canvas size of 500X500. · The program asks the user to enter a 3 digit number. · The program then checks the value of the first and last digit of the number. · If the first and last digits are even, it makes the background green and displays the three digit number at the mouse pointer. · If the two digits are odd, it...
Write the program in java Write a program that does basic encrypting of text. You will...
Write the program in java Write a program that does basic encrypting of text. You will ask the user the filename of a text file which contains a few sentences of text. You will read this text file one character at a time, and change each letter to another one and write out to an output file. The conversion should be done a -> b, b->c , … z->a, A->B, B->C, …. Z->A. This means just shift each letter by...
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: Create a method to fill the 2-dimensional array with (random numbers, range 0 - 30). The array has rows (ROW) and columns (COL), where ROW and COL are class constants. Create a method to print the array. Create a method to find the largest element in the array Create a method to find the smallest element in the array Create a method to...
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: 1. Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. 2. Create a method to print the array. 3. Create a method to find the largest element in the array 4. Create a method to find the smallest element in the array 5....
Write a Java program that will use a two-dimensional array and modularity to solve the following...
Write a Java program that will use a two-dimensional array and modularity to solve the following tasks: Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. Create a method to print the array. Create a method to find the largest element in the array Create a method to find the smallest element in the array Create a method to find...
Write a java program that does the following: a) The user will enter data such as...
Write a java program that does the following: a) The user will enter data such as client name and client balance. The user can stop inputting data by entering "stop". The program should store the user inputs as a data member of an array. The type of this array is a class named ClientData. Below the output should be displayed by the program. The parts in bold are inputs from the user and not hard coded in the program Client...
Write a java program to solve Towers of Hanoi with the condition that there are "m"...
Write a java program to solve Towers of Hanoi with the condition that there are "m" number of rods and "n" number of disks. Where m >= 3 and n >=1.
Recursion practice Write a Java program with functions for each of the following problems. Each problem...
Recursion practice Write a Java program with functions for each of the following problems. Each problem should be solved by writing a recursive function. Your final program should not have any loops in it. All of your solutions should be in a single .java file. The main function of the file should demonstrate each of your solutions, by running several tests and producing the corresponding outputs. Write a recursive method to 1. calculate power of a give number 2. multiply...
Write a Java program that will use a two-dimensional array to solve the following tasks: 1....
Write a Java program that will use a two-dimensional array to solve the following tasks: 1. Create a method to generate a 2-dimensional array (random numbers, range 0 - 500). The array has ROW rows and COL columns, where ROW and COL are class constants. 2. Create a method to print the array. 3. Create a method to find the largest element in the array 4. Create a method to find the smallest element in the array 5. Create a...
Write a program in java that does the following: Create a StudentRecord class that keeps the...
Write a program in java that does the following: Create a StudentRecord class that keeps the following information for a student: first name (String), last name (String), and balance (integer). Provide proper constructor, setter and getter methods. Read the student information (one student per line) from the input file “csc272input.txt”. The information in the file is listed below. You can use it to generate the input file yourself, or use the original input file that is available alone with this...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT