Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

% Function Name: recursiveParens % % Inputs (1): - (char) A string including som

ID: 3539003 • Letter: #

Question

% Function Name: recursiveParens

%

% Inputs (1): - (char) A string including some number of parentheses

% (and possibly other characters)

% Outputs (2): - (logical) True if the parentheses are not unbalanced at

% ANY point in the string, and false otherwise

% (double) A double representing the imbalance in

% parentheses

%

% Function Description:

% Write a function called "matchParens" that takes in a string that has

% some number of parentheses and determines whether or not

% the expression is valid as well as the total imbalance of the string.

%

% An expression is valid if it contains the same number of open and

% closed parentheses while containing no open parentheses which have no

% matching closed parentheses and vice versa. The total imbalance of the

% expression is then defined as the number of open parentheses minus the

% number of closed parentheses.

%

% For example: '(())', '()()()', and '((())((())))' are all valid strings

% that should return true and an imbalance of 0.

%

%

% However: '()))' is unbalanced and should return false and -2

%

% '(((((' is unbalanced and should return false and 5

%

% '())(' is unbalanced and should return false and 0

%

% Be careful of strings that have the same number of open and closing

% parentheses but are imbalanced at some point in the string,

% like in the last example.

%

% Additionally, do not assume that an input string is composed entirely

% of parentheses. Any character that is not '(' or ')' should have no

% bearing on the outputs of your function.

%

% Constraints:

% - Do not use the sum(), strfind(), findstr(), find(), or any other

% similar functions. They will most likely overcomplicate the problem

% anyway.

% - You must use recursion to solve this problem.

%

% Test Cases:

%

% str1 = '(())())))(())'

% str2 = '(k((vx)((z/)))7)'

% str3 = ''

%

% [log1 imbalance1] = recursiveParens(str1);

% log1 => false

% imbalance1 => -3

%

% [log2 imbalance2] = recursiveParens(str2);

% log2 => true

% imbalance2 => 0

%

% [log3 imbalance3] = recursiveParens(str3);

% log3 => true

% imbalance2 => 0

Explanation / Answer

function[logic_out1,double_out2] = recursiveParens(string_in)



string_len = length(string_in);

count=0;

for i=1:string_len

if string_in(i)=='('

count=count+1;

end

if string_in(i)==')'

count=count-1;

end

end


logic_out1=~(count==0);

double_out2=count;

end