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
Execution of the program segment starts at the first statement (statement 0) and concludes when it reaches a RETURN statement. We call such a sequence an "execution path."
In order to optimize the code, we want to find the smallest loop in the program segment that can be executed. A loop is defined to be a set of statements such that
- Only one statement in the loop (the entry point) may be immediately preceded in an execution path by a statement that is not in the loop.
- If a loop contains statement 0, then statement 0 must be the entry point for that loop.
- If a statement S is in the loop, then there is an execution path that executes S and then, without executing any statement outside the loop, executes every statement (including S) in the loop at least once.
Definition
- Class:
- Loopy
- Method:
- minLoop
- Parameters:
- String[]
- Returns:
- int
- Method signature:
- int minLoop(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: 0
Execution immediately returns, so there is no loop.{"IF 1 ELSE 2","IF 1 ELSE 2","RETURN"}Returns: 1
Statement 1 forms a loop.{"IF 1 ELSE 2","RETURN", "IF 3 ELSE 2", "IF 2 ELSE 3"}Returns: 0
No execution path that includes either statement 2 or 3 can ever reach a RETURN statement. The only legal execution path is statement 0 followed by statement 1 so there is no loop.{"IF 1 ELSE 2","IF 3 ELSE 3","IF 4 ELSE 1", "IF 4 ELSE 5","RETURN","IF 0 ELSE 6", "IF 6 ELSE 6","IF 7 ELSE 2"}Returns: 5
Statements 0, 1, 2, 3, and 5 form a loop whose entry point is statement 0. Note that no execution path contains statement 7, so statement 2 is never preceded by a non-loop statement.