Question

Please use the JAVA code attached as an input to the program that must be created IN JAVA.

Instructions of the program:

Write a non-recursive program using a stack that evaluates arithmetic expressions over the set Zs= 10, 1, 2). Assume that the

java code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *

 */

import java.util.Random;

public class Rand_Z3_Exp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        int m = 100;
        
        System.out.println(rand_gen_z3Exp(m));
        
        System.exit(0);
}
    
   
    public static String rand_gen_z3Exp (int n){
        
        if (n<=0)
            return "";
        
        //possible symbols in the expression
        String symbols = "012(+-*)";
        //possible symbols after each current symbol
        String[] succ = {"*+-)","*+-)", "*+-)", "012(+-", "012(", "012(", "012(", ")+-*"};
        //Ouput string initialized;
        String z3_exp = "";
        
        //number of left apparantheses generated so far
        int num_of_lp = 0;
        //randomly generate first symbol in the output
        Random r = new Random();        
        int symbol_no = r.nextInt(6);
        char first_symbol = symbols.charAt(symbol_no);
        if (symbol_no == 3)
            num_of_lp++; 
        z3_exp += first_symbol;
        
        // The last symbol generated
        char last_symbol = first_symbol;
        // The main loop that generates the rest of the expression
        for(int i=1; i<n-num_of_lp; i++){
            
            String s = succ[symbols.indexOf(last_symbol)]; 

            // genrating the next symbol in the expression and
            // make sure that it conforms to format of loogical expressions
            char next_symbol;
            boolean again;
            do{
                again = false;
                next_symbol = s.charAt(r.nextInt(s.length()));
                switch (next_symbol){
                    case ')':   // All parantheses seen so far matched
                                // ) is not allowed for next symbol
                                if (num_of_lp==0){ 
                                    again = true;
                                }
                                else
                                    num_of_lp--;
                                break;
                    case '(':   num_of_lp++; 
                                break;
                    default:
                }
            
            }while(again);
            
            z3_exp += next_symbol;
            last_symbol = next_symbol;
        }
        
        // check if the last symbol is an operator or '(' and hence need an operand to complete the expression
        if (last_symbol=='(' ||  last_symbol=='*' ||  last_symbol=='+' ||  last_symbol=='-')        
            z3_exp += symbols.charAt(r.nextInt(3));
        
        // adding necessary closing )'s
        for(int i=0; i<num_of_lp; i++)
            z3_exp += ')';
        
        /* removing unneeded parentheses of the form "(z)" where z = 0, 1 , or 2.
        for(int i=0; i<3; i++)
            z3_exp = z3_exp.replace("("+i+")", String.valueOf(i));*/
        
        return z3_exp;
    }

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

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

import java.util.Random;

import java.util.Stack;

public class RandZ3Exp {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
  
int m = 100;
String exp = rand_gen_z3Exp(m);
System.out.println(exp);
  
System.out.println(evaluate(exp));
  
System.exit(0);
}
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((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) % 3;
case '-':
return (a - b)%3;
case '*':
return (a * b)%3;
}
return 0;
}
  
public static int evaluate(String expression)
{
char[] tokens = expression.toCharArray();
  
// Stack for numbers: 'values'
Stack<Integer> values = new Stack<Integer>();
  
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
  
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] == '*')
{
// 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();
}

public static String rand_gen_z3Exp (int n){
  
if (n<=0)
return "";
  
//possible symbols in the expression
String symbols = "012(+-*)";
//possible symbols after each current symbol
String[] succ = {"*+-)","*+-)", "*+-)", "012(+-", "012(", "012(", "012(", ")+-*"};
//Ouput string initialized;
String z3_exp = "";
  
//number of left apparantheses generated so far
int num_of_lp = 0;
//randomly generate first symbol in the output
Random r = new Random();
int symbol_no = r.nextInt(6);
char first_symbol = symbols.charAt(symbol_no);
if (symbol_no == 3)
num_of_lp++;
z3_exp += first_symbol;
  
// The last symbol generated
char last_symbol = first_symbol;
// The main loop that generates the rest of the expression
for(int i=1; i<n-num_of_lp; i++){
  
String s = succ[symbols.indexOf(last_symbol)];

// genrating the next symbol in the expression and
// make sure that it conforms to format of loogical expressions
char next_symbol;
boolean again;
do{
again = false;
next_symbol = s.charAt(r.nextInt(s.length()));
switch (next_symbol){
case ')': // All parantheses seen so far matched
// ) is not allowed for next symbol
if (num_of_lp==0){
again = true;
}
else
num_of_lp--;
break;
case '(': num_of_lp++;
break;
default:
}
  
}while(again);
  
z3_exp += next_symbol;
last_symbol = next_symbol;
}
  
// check if the last symbol is an operator or '(' and hence need an operand to complete the expression
if (last_symbol=='(' || last_symbol=='*' || last_symbol=='+' || last_symbol=='-')
z3_exp += symbols.charAt(r.nextInt(3));
  
// adding necessary closing )'s
for(int i=0; i<num_of_lp; i++)
z3_exp += ')';
  
/* removing unneeded parentheses of the form "(z)" where z = 0, 1 , or 2.
for(int i=0; i<3; i++)
z3_exp = z3_exp.replace("("+i+")", String.valueOf(i));*/
  
return z3_exp;
}

}

RandZ3Exp.java 3 20 To change this license header, choose License Headers in Project Properties. import java.util.Random; 9 i

Add a comment
Know the answer?
Add Answer to:
Please use the JAVA code attached as an input to the program that must be created IN JAVA. Instru...
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
  • Please use the JAVA code attached as an input to the program that must be created...

    Please use the JAVA code attached as an input to the program that must be created IN JAVA. Instructions of the program: java code: /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * */ import java.util.Random; public class Rand_Z3_Exp { /** * @param args the command line arguments */ public static void main(String[] args) {...

  • Here is the code I have so far. I'm trying to figure out how to implement...

    Here is the code I have so far. I'm trying to figure out how to implement a boolean and use precedence. The 2nd expression should be 14 but it comes out as 28 so I'm definitely not understanding. #include <stack> #include <iostream> #include <string> using namespace std; // Function to find precedence of // operators. int precedence(char op) {    if (op == '+' || op == '-')        return 1;    if (op == '*' || op ==...

  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

  • This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming...

    This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming language. You will write a program that reads an infix expression, converts it to a postfix expression, evaluates the postfix expression, and prints out the answer. You must define and implement your own Stack class and a Calculator class. Your Stack class supports standard basic stack operations and you can implement it with an array or a linked list. You should create a class...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • C++ Progrmaming Ch. 5 Stacks ** Please actually help! I have asked this question three times...

    C++ Progrmaming Ch. 5 Stacks ** Please actually help! I have asked this question three times now and every response has not compiled and has many errors. *** Develop an expression manager that can do a balanced symbol check. Your program will read three different mathematical expressions from the user that are the followings: string expression = "{(0+1)*(2+3)}"; string expression = "{(0+1)+[4*(2+3)]}"; string expression = "{(0+1)+[4*(2+3)}}"; As you notice the expressions contain the following symbols: { , }, ( ,...

  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • I'm having trouble writing this code, can some help me? Step 1: Capturing the input The...

    I'm having trouble writing this code, can some help me? Step 1: Capturing the input The first step is to write a functionGetInput()that inputs the expression from the keyboard and returns the tokens---the operands and operators---in a queue. You must write this function. To make the input easier to process, the operands and operators will be separated by one or more spaces, and the expression will be followed by #. For example, here’s a valid input to your program: 6...

  • Question: Write a Java program for Evaluating Postfix Expression 1. Input a postfix expression from user....

    Question: Write a Java program for Evaluating Postfix Expression 1. Input a postfix expression from user. 2. Evaluate expression using double stack made of your own linked list. 3. Show the result of expression or error if incorrect. Evaluating Postfix Expression Input an expression: 2 10 + 9 6 - / Evaluating Postfix Expression Input an expression: 20 10 + 9 6 - 1 Evaluating Postfix Expression Input an expression: 2 10 + 9 - / Result = 4.0 Result...

  • i want similar for this code to solve two questions : 1- Write a program to...

    i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c;...

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