0

I have a mathematical formulas in a give form as below in Java (Of course not simple as this one):

String equation = "x^2 + 3*y + 1";

I want to generate z values from x and y array's with having same size n such that z = equation(x,y) which also have size n.For example z = { x[0]^2 + 3 * y[0] + 1 , ..... , x[n-1]^2 + 3 * y[n-1] + 1 }.

What is the best approach in Java without outside libraries that would help me evaluate the every equation with respect to every integer set of any number of variables such as x and y?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Orkun Kocyigit
  • 1,137
  • 10
  • 21
  • Your question is not clear? Do you have X[] and Y[] predefined? What's wrong with: `for(int i=0; i< n; i++){ z[i] = evaluate(x[i], y[i]); }` – rocketboy Jul 30 '13 at 07:23
  • If you can't (or don't want to) use the built in `evaluate`, you need to write a tokeniser, lexical analyser and parser. Google these terms - and 'recursive descent parser' and you should be on your way. – Bathsheba Jul 30 '13 at 07:24
  • Yes all values of X and Y is pre-defined. – Orkun Kocyigit Jul 30 '13 at 07:26
  • So tiresome. This question has been asked many times. – duffymo Jul 30 '13 at 11:50

2 Answers2

1

In case you want to do everything from scratch you ll need to come up with an equation parser.

From there you use an Enum :

    enum Operation{ADD, SUBTRACT;

        public int evaluate(int operand1, int operand2) throws IllegalOperationException {
            switch(this) {
            case ADD: return operand1 + operand2;
            case SUBTRACT: return operand1 - operand2;
            default:
                break;
            }
            throw new IllegalOperationException();
        }

        public static Operation getOperator(String operator) throws IllegalOperationException{
            for(Operation o: Operation.values()){
                if(o.toString().equals(operator)){
                    return o;
                }
            }
            throw new IllegalOperationException();
        }
    }; 

So, parse your equation using a stack/queue and then for each operator(op) basically do:

Operation.getOperator(op).evaluate(r1, r2);

OR

Replace x and y with x[i] and y[i] and pass the constructed string to built in javascript engine, in case you are using jdk1.6 or higher.

ScriptEngineManager sm = new ScriptEngineManager();
ScriptEngine en = sm.getEngineByName("JavaScript");
String expression = //your expression with values;
System.out.println(engine.eval(expression));
rocketboy
  • 9,573
  • 2
  • 34
  • 36
0
public int[] solveEquation(int[] x, int[] y){
    if (x == null || y == null || x.length != y.length){
        return null;
    }
    int[] z = new int[x.length];
    for (int i=0; i<x.length; i++){
        z[i] = x[i]^2 + 3*y[i] + 1;
    }
    return z;
}
Raunak Agarwal
  • 7,117
  • 6
  • 38
  • 62