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...
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 IN JAVA. Instru...

    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 ==...

  • JAVA TIC TAC TOE - please help me correct my code Write a program that will...

    JAVA TIC TAC TOE - please help me correct my code Write a program that will allow two players to play a game of TIC TAC TOE. When the program starts, it will display a tic tac toe board as below |    1       |   2        |   3 |    4       |   5        |   6                 |    7      |   8        |   9 The program will assign X to Player 1, and O to Player    The program will ask Player 1, to...

  • 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;...

  • 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 program that replace repeated three characters in a string by the character followed by 3...

    Write a program that replace repeated three characters in a string by the character followed by 3. For example, the string aabccccaaabbbbcc would become aabc3ca3b3cc. When there are more than three repeated characters, the first three characters will be replaced by the character followed by 3. You can assume the string has only lowercase letters (a-z). Your program should include the following function: void replace(char *str, char *replaced); Your program should include the following function: void replace(char *str, char *replaced);...

  • 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:...

  • C Language program. Please follow the instructions given. Must use functions, pointers, and File I/O. Thank...

    C Language program. Please follow the instructions given. Must use functions, pointers, and File I/O. Thank you. Use the given function to create the program shown in the sample run. Your program should find the name of the file that is always given after the word filename (see the command line in the sample run), open the file and print to screen the contents. The type of info held in the file is noted by the word after the filename:...

  • Total point: 15 Introduction: For this assignment you have to write a c program that will...

    Total point: 15 Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result. What should you submit? Write all the code in a single file and upload the .c file. Problem We as humans write math expression in infix notation, e.g. 5 + 2 (the...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

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