Forum

Post 28.04.2009   # 1
Subject CodeFu 2009 Round 1 - Problem 300
300. Stack Machine

Here, you only need to simulate the instructions of the Stack machine.
You can even use the java.util.Stack class for the simulation, so no need for your custom Stack implementation.
Just iterate over all the instructions, and depending on the "opcode" of the instruction, do what is required.
Here is the complete solution:

public class StackMachine {

public static final String ERROR = "[ERROR]";
public static final String EMPTY = "[EMPTY]";

public String getOutput(String[] instructions) {

Stack<Long> stack = new Stack<Long>();

StringBuffer sb = new StringBuffer("");

for (int i = 0; i < instructions.length; ++i) {
String ins = instructions[i];
if ("POP".equals(ins)) {
if (stack.size() == 0) {
sb.append(ERROR);
} else {
stack.pop();
}
} else if ("ADD".equals(ins)) {
if (stack.size() < 2) {
sb.append(ERROR);
} else {
stack.push(stack.pop() + stack.pop());
}
} else if ("MUL".equals(ins)) {
if (stack.size() < 2) {
sb.append(ERROR);
} else {
stack.push(stack.pop() * stack.pop());
}
} else if ("SUB".equals(ins)) {
if (stack.size() < 2) {
sb.append(ERROR);
} else {
stack.push(stack.pop() - stack.pop());
}
} else if ("SWAP".equals(ins)) {
if (stack.size() < 2) {
sb.append(ERROR);
} else {
long a = stack.pop();
long b = stack.pop();
stack.push(a);
stack.push(b);
}
} else if ("PRINT".equals(ins)) {
if (stack.size() ==0) {
sb.append(EMPTY);
} else {
sb.append("[" + stack.peek() + "]");
}
} else if (ins.startsWith("PUSH")) {
String[] a = ins.split(" ");
stack.push(Long.parseLong(a[1]));
}
}
return sb.toString();
}
}

bilievsk is offline Reply

Please login to post reply.