My assignment is to create a function called "roll" that implements the roll(n,k) operation on the specified stack. My function should check that n and k are both nonnegative and that n is not larger than the stack size; if either of these conditions are violated, the function should throw a runtime exception with the message "roll: argument out of range" Here is what I have so far:
import java.util.Stack;
public class PostScript{
public static void main(String [] args){
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
Stack<String> s = new Stack<String>();
s.push("A"); s.push("B"); s.push("C"); s.push("D");
System.out.println("Initial : " + s);
roll(s,n,k);
System.out.println("after roll(" + n + ", " + k + "): " + s);
}
public static void roll(Stack<String> stack, int n, int k){
}
}
Here are some example test runs:
$ java PostScript 4 1\
Initial : [A, B, C, D]\
after roll(4, 1): [D, A, B, C]
$ java PostScript 3 2\
Initial : [A, B, C, D]\
after roll(3, 2): [A, C, D, B]
$ java PostScript 2 4\
Initial : [A, B, C, D]\
after roll(2, 4): [A, B, C, D]
The effect of applying roll(n,k) is to rotate the top n elements of a stack by k positions, where the general direction of the rotation is toward the top of the stack. More specifically, roll(n,k) has the effect of removing the top n elements, cycling the top element to the last position k times, and then replacing the reordered elements on the stack. For example,
roll(4,1) roll(3,2) roll(2,4)
| D | | C | | D | | B | | D | | D |
| C | | B | | C | | D | | C | | C |
| B | -> | A | | B | -> | C | | B | -> | B |
| A | | D | | A | | A | | A | | A |