Problem Statement
We have a program segment and want to analyze the control flow through it.
We have already replaced the
actual code with simpler code that captures just the control logic. The
code we want to analyze consists of a sequence of statements in which each statement
is one of the following two types:
- IF target1 ELSE target2
- RETURN
We want to find all the dead code. A statement is "dead" if there is no execution path that contains it, where an execution path must start at the first statement (statement 0) in the segment and conclude by executing a RETURN statement. Create a class DeadCode that contains a method deadCount that is given a String[] code containing the sequence of statements and that returns the number of dead statements.
Definition
- Class:
- DeadCode
- Method:
- deadCount
- Parameters:
- String[]
- Returns:
- int
- Method signature:
- int deadCount(String[] code)
- (be sure your method is public)
Constraints
- code will contain between 1 and 50 elements inclusive.
- Each element of code will be one of the two forms above.
- Each RETURN statement has no spaces.
- Each IF statement has exactly 3 spaces.
- Each target1 and target2 will be an integer with no extraneous leading zeroes.
- Each target1 and target2 will be between 0 and n-1 inclusive, where n is the number of elements in code.
Examples
{"RETURN", "IF 0 ELSE 1"}Returns: 1
Execution immediately returns, so statement 1 cannot be reached.{"IF 1 ELSE 2","IF 1 ELSE 2","RETURN"}Returns: 0
The sequence 0, 2 and the sequence 0, 1, 1, 2 are examples of legal execution paths. Every statement is in a legal execution path so there is no dead code.{"IF 1 ELSE 2","RETURN", "IF 3 ELSE 2", "IF 2 ELSE 3"}Returns: 2
Statements 2 and 3 are dead. No execution path that includes either of them can ever reach a RETURN statement.