import java.util.*;
public class LoopMaster {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfCommands = Integer.parseInt(scanner.nextLine());
List commands = new ArrayList();
for (int i = 0; i < numberOfCommands; i++) {
commands.add(scanner.nextLine().trim());
}
processCommands(commands);
}
private static void processCommands(List commands) {
Stack loopIterations = new Stack();
Stack currentIterations = new Stack();
StringBuilder output = new StringBuilder();
int commandIndex = 0;
while (commandIndex < commands.size()) {
String command = commands.get(commandIndex);
if (command.startsWith("for")) {
int times = Integer.parseInt(command.split(" ")[1]);
loopIterations.push(times);
currentIterations.push(0);
} else if (command.equals("do")) {
// No operation for "do"
} else if (command.equals("done")) {
int current = currentIterations.pop() + 1;
int maxIterations = loopIterations.pop();
if (current < maxIterations) {
loopIterations.push(maxIterations);
currentIterations.push(current);
commandIndex = findLoopStart(commands, commandIndex);
continue;
}
} else if (command.startsWith("break")) {
int breakCondition = Integer.parseInt(command.split(" ")[1]);
if (currentIterations.peek() + 1 == breakCondition) {
loopIterations.pop();
currentIterations.pop();
commandIndex = findLoopEnd(commands, commandIndex);
}
} else if (command.startsWith("continue")) {
int continueCondition = Integer.parseInt(command.split(" ")[1]);
if (currentIterations.peek() + 1 == continueCondition) {
int maxIterations = loopIterations.peek();
int current = currentIterations.pop() + 1;
if (current < maxIterations) {
currentIterations.push(current);
commandIndex = findLoopStart(commands, commandIndex);
}
continue;
}
} else if (command.startsWith("print")) {
String message = command.substring(command.indexOf("\"") + 1, command.lastIndexOf("\""));
output.append(message).append("\n");
}
commandIndex++;
}
System.out.print(output.toString());
}
private static int findLoopStart(List commands, int currentIndex) {
int nestedLoops = 0;
for (int i = currentIndex - 1; i >= 0; i--) {
if (commands.get(i).equals("done")) {
nestedLoops++;
} else if (commands.get(i).equals("do")) {
if (nestedLoops == 0) {
return i;
}
nestedLoops--;
}
}
return 0;
}
private static int findLoopEnd(List commands, int currentIndex) {
int nestedLoops = 0;
for (int i = currentIndex + 1; i < commands.size(); i++) {
if (commands.get(i).equals("do")) {
nestedLoops++;
} else if (commands.get(i).equals("done")) {
if (nestedLoops == 0) {
return i;
}
nestedLoops--;
}
}
return commands.size();
}
}
Java
Loop Master - Codevita Telegram -
t.me/codingsolution_IT