Question

I need to write a code that takes a string input and turns it, or something to that effect, into a valid unary equation with addition to verify if it is valid. I'm confused, could anyone point me in the direction of understanding this? An example would be: 111+1111=11111+1+1 is the statement 3+4=5+1+1 which is valid. My other question would be how to use stacks to do unary operations.

Was it helpful?

Solution

If you are limited to this language then your can write a simple parser using a number of methods. You can first split your String

String[] parts = eqn.split("=");

Then split each part:

String[] left = parts[0].split("\\+");
String[] right = parts[1].split("\\+");

Now you can simply count the lengths of the strings:

int leftside = 0;
for (String l : left) {
    leftside += l.length;
}

and so on for the right side and see if they are equal.

There are many other ways you can tackle this.

Basically you have to write a parser. You might want to use a character-by-character scanner, or use regexes or a generic tool such as ANTLR. It depends on your final goal and whether it is likely to change. Are you likely to have characters other than 1, +, =, for example?

My guess is this is homework. And I guess that you are expected to read character-by-character and push() each character on a stack. Then you have to pop() the stack when you encounter certain conditions.I'm not going to do this for you...

OTHER TIPS

Another possible solution.

String input = "111+1111=11111+1+1";
    String[] parts = input.split("=");

    Pattern pattern = Pattern.compile("1");
    Matcher  matcherLeft = pattern.matcher(parts[0]);
    Matcher matcherRight = pattern.matcher(parts[1]);
    int leftTotal = 0;
    while (matcherLeft.find())
        leftTotal++;

    int rightTotal = 0;
    while (matcherRight.find())
        rightTotal++;

    if(leftTotal == rightTotal)
        System.out.println("Valid");
    else
        System.out.println("Invalid");

Starts out by splitting the string in to the left and right side of the equations. Then simply counts the number of 1's in each part and does a comparison. There's definitely better ways to do this, but with this example it's pretty easy to see what is going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top