-1

I'm building a calculator that can solve formula's as a project of mine in which i encountered the problem that a string such as 2x+7 will get tokenized as "2x","+" ,"7".

I need to properly split it into constants and variables which means 2x should be "2" , "x" . How do i do this without it affecting even complex formulas which include Sin and Cos functions etc?

For example i want 16x + cos(y) to be tokenized as "16" , "x" , "+" , "cos" , "(" , "y" , ")"

Emma
  • 27,428
  • 11
  • 44
  • 69
  • start by parsing functions like sin/cos, by the time you'll finish with them you'll have only variables like `x` – Nir Alfasi Jun 30 '19 at 04:58

1 Answers1

0

This problem would be pretty complicated, and this answer is just an example.

Maybe, we would want to figure out what types of equations we might have, then we would start designing some expressions. For instance, we can have a look at this:

([a-z]+)|([-]?\d+)|[-+*\/]

Demo 1

Or:

([a-z]+)|([-]?\d+)|([-+*\/])|(\(|\))

Demo 2

Example

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "([a-z]+)|([-]?\\d+)|([-+*\\/])";
final String string = "2x+7\n"
     + "2sin(2x + 2y) = 2sin(x)*cos(2y) + 2cos 2x * 2sin 2y\n"
     + "2sin(2x - 2y) = -2tan 2x / cot -2y + -2cos -2x / 2sin 2y\n";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

I really don't have any suggestion as to how it would be best to architect a solution for this problem. But, maybe you would want to categorize your equations first, then design some classes/methods to process each category of interest, and where regex was necessary, you can likely design one/multiple expressions for desired purposes that you wish to accomplish.

Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    I see you have grouped the the formula as a whole from regex but wouldnt it be easier if we perform it only on the strings that are inconveniently left by the string tokenizer method , such as 19x5ycos, 20xysin i want them to be entered into a vector as 19, x, 5, y, cos and 20, x , y, sin because i have used 3 groups to save constants, variable and functions accordingly – Laventio_19 Jun 30 '19 at 06:11
  • 1
    I was just stating my idea, I'm clueless as to how to implement it – Laventio_19 Jun 30 '19 at 17:26