0

I've tried to solve this question for the past couple of hours and I just don't understand it. I know there must be a sort of mathematical calculation to calculate this but I don't know how to exactly calculate it. I know this code does not make sense because I'm completely lost, I would appreciate any hints or help for this to help me get closer to the solution.

I asked my professor and he told me a hint about it being similar to a permutation/combination using alphabet such as 26^3 for 3 different combinations but this did not help me much.

What I know:

  1. There are 796 characters for the input given in the string and I must find ALL possible ways that 796 characters can be in a balanced parenthesis form.

  2. Since it must start with '(' and end with ')' there must be 2 brackets for each case. So it can be '()()(xc)(cvs)'. Thus that means the mathematical calculation must involve 2*(something) per char(s) since it has to be balanced.

  3. I need to use the remainder(%) operator to recursively find every case but how do I do that when I take a char in not an int?

What I don't know:

  1. How will I analyze each case? Won't that take a long time or a lot of code without a simple formula to calculate the input?

  2. Would I need a lot of if-statements or recursion?

Question:

Let Σ = {), (}. Let L ⊆ Σ* be the set of strings of correctly balanced parentheses. For example, (())() is in L and (()))( is not in L. Formally, L is defined recursively as follows.

ε ∈ L

A string x ≠ ε is in L if and only if x is of the form (y)z, where y and z are in L.

n is a specific 3 digit number between 0 and 999.

Compute f(n) mod 997

Some facts you might find useful: if n1, n2 is a member of N(natural number) then,

(n1 x n2) mod 997 and (n1 + n2) mod 997

n = 796 (this is specific for me and this will be the given input in this case)

So I must "compute f(796) mod 997 = ?" using a program. In this case I will simply use java for this question.

Code:

import java.util.*;
public class findBrackets
{

    public static void main(String[] args)
    {

        String n;
        int answer = 0;
        Scanner input = new Scanner(System.in);

        System.out.println("Input String");
        n = input.nextLine();

           // probably wrong because a string can start as x(d))c(()...

        for(int i = 0; i < n; i++)
        {
           if(n[i] != '(' || n[i] != ')' || n[i] != null || n[i] != " ") { 

             answer = 2 * (Integer.parseInt(n[i]); // how can i calculate if its a char

              // i have to use mod % operator somewhere but I don't know where?
           }

        }

       System.out.println("f(796) mod 997 = " + answer);

    }
 }
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
geforce
  • 79
  • 1
  • 1
  • 12
  • 1
    The "Question:" part gives a good formal definition of the set of strings with balanced parentheses, but no definition at all of what f(n), the thing you're supposed to compute, is supposed to be. Did you accidentally leave something out? I'm really not clear on what you're supposed to be computing, and the definition of f(n) would be nice. – ajb Sep 17 '14 at 19:21
  • It looks recursive in nature. – StackFlowed Sep 17 '14 at 19:23
  • The question is right it is just really confusing because of how its written – geforce Sep 17 '14 at 20:03
  • It's your fault if the question is confusing. What is f(n)? Is it the number of length n strings with balanced parentheses? – Teepeemm Sep 18 '14 at 02:46

3 Answers3

2

You might find the following fact useful: the number of strings of n pairs of balanced parentheses is given by the nth Catalan number and its exact value is

(2n)! / (n! (n + 1)!)

You should be able to directly compute this value mod 997 by using the hint about how products and sums distribute over modulus.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • The hint about how products and sums distribute over modulus is the equation you provided or is it something I have to research? Also it is not the number of strings, there is 1 string... but it has 796 characters. – geforce Sep 17 '14 at 20:02
0

I'm still not quite sure exactly what you're asking, but validating as to whether or not the parentheses are valid placement can be done using the following method. I used a similar one to go through hundred-page papers to ensure all parentheses were closed properly in the old days.

public static boolean isValid(String s) {
    int openParens = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            // we found an open paren
            openParens++;
        } else if (s.charAt(i) == ')') {
            // we can close a paren
            openParens--;
        }
        if (openParens < 0) {
            // we closed a paren but there was nothing to close!
            return false;
        }
    }
    if (openParens > 0) {
        // we didn't close all parens!
        return false;
    }
    // we did!
    return true;
}
Compass
  • 5,867
  • 4
  • 30
  • 42
0

You need to do implement this:

public static void main (String[]args) {
    String str = "((1+2)*(3+4))-5";
    if(isValid(str)){
        expandString(str);
    }
}

public static boolean isValid(String s) {
    int totalParenthesis = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '(') {
            totalParenthesis++;
        } else if (s.charAt(i) == ')') {
            totalParenthesis--;
        }
        if (totalParenthesis < 0) {
            return false;
        }
    }
    if (totalParenthesis != 0) {
        return false;
    }
    return true;
}

private static void expandString(String str) {
    System.out.println("Called with : "+str);
    if(!(str.contains("("))){
        evalueMyExpresstion(str);
        return;
    }
    String copyString=str;
    int count=-1,positionOfOpen=0,positionOfClose=0;
    for(Character character : str.toCharArray()) {
        count++;
        if(count==str.toCharArray().length){
            evalueMyExpresstion(str);
            return;
        } else if(character.equals('(')) {
            positionOfOpen=count+1;
        } else if(character.equals(')')) {
            positionOfClose=count;
            copyString = str.substring(0, positionOfOpen - 1) + evalueMyExpresstion(
                        str.substring(positionOfOpen, positionOfClose)) + str.substring(positionOfClose + 1);
            System.out.println("Call again with : "+copyString);
            expandString(copyString);
            return;
        }
    }
}

private static String evalueMyExpresstion(String str) {
    System.out.println("operation : "+str);
    String[] operation;
    int returnVal =0;
    if(str.contains("+")){
        operation = str.split("\\+");
        returnVal=Integer.parseInt(operation[0])+ Integer.parseInt(operation[1]);
        System.out.println("+ val : "+returnVal);
        return Integer.toString(returnVal);
    } else if (str.contains("*")){
        operation = str.split("\\*");
        returnVal=Integer.parseInt(operation[0])* Integer.parseInt(operation[1]);
        System.out.println("* val : "+returnVal);
        return Integer.toString(returnVal);
    } else if (str.contains("-")){
        operation = str.split("\\-");
        returnVal=Integer.parseInt(operation[0])- Integer.parseInt(operation[1]);
        System.out.println("- val : "+returnVal);
        return Integer.toString(returnVal);
    }
    System.out.println(str);
    return Integer.toString(returnVal);
}

Output looks like:

Called with : ((1+2)*(3+4))-5
operation : 1+2
+ val : 3
Call again with : (3*(3+4))-5
Called with : (3*(3+4))-5
operation : 3+4
+ val : 7
Call again with : (3*7)-5
Called with : (3*7)-5
operation : 3*7
* val : 21
Call again with : 21-5
Called with : 21-5
operation : 21-5
- val : 16
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • Missed a small bit of logic in your `isValid`: `totalParenthesis` going below 0 should it invalid. Example: ")(" should be invalid. – Compass Sep 17 '14 at 20:33
  • Yes will make that change ... Good catch ! – StackFlowed Sep 17 '14 at 20:37
  • Good code but unfortunately it wont work with this question because there are many cases to do manually – geforce Sep 17 '14 at 22:18
  • This is an sample code you can split string based on regular expression for Punctuation. These are are punctuations char [][!"#$%&'()*+,./:;<=>?@\^_`{|}~-] – StackFlowed Sep 18 '14 at 01:11