Hi! I am having a small (and possibly really simple) problem with my code (I am using java)...
Here is the assignment given by my teacher:
Use a Stack to write a method allSeqs(int max, int len) that will generate all sequences, consisting of the numbers between 1 and max, of length len. For instance, calling allSeqs(3,2) gives: [1, 1][1, 2][1, 3][2, 1][2, 2][2, 3][3, 1][3, 2][3, 3] while calling allSeqs(2, 4) gives [1, 1, 1, 1][1, 1, 1, 2][1, 1, 2, 1][1, 1, 2, 2][1, 2, 1, 1][1, 2, 1, 2][1, 2, 2, 1][1, 2, 2, 2][2, 1, 1, 1][2, 1, 1, 2][2, 1, 2, 1][2, 1, 2, 2][2, 2, 1, 1][2, 2, 1, 2][2, 2, 2, 1][2, 2, 2, 2]
You can use a backtracking method, very similar to what we did for the N Queens problem: Push the proper number of 1's onto a Stack, and then repeatedly
print out the stack contents (that's one permutation), and
pop the top element, and if it's not equal to max, add one to it, and push it back.
And here is my code:
import java.util.*; public class NewStack { private Stack<Integer> s; public String toString() { String result = "[ "; while ( !s.isEmpty()) result = result + s.pop() + ","; result = result + "]"; return result; } public void allSeqs(int max, int len) { System.out.println(s); while (s.size() < len){ s.push(1); } System.out.println(s); for (int i=0; i<len; i++){ try{ int a = s.pop(); if (a < max) { a = a + 1; s.push(a); } else { s.push(1); } System.out.print(s); }//end try block catch (NullPointerException e) { System.out.println("The last slot has been reached, the next one is empty so, we are done!"); } }//end for loop } //end method public static void main(String[] args) { NewStack nt = new NewStack(); nt.allSeqs(2,3); } }
It compiles, but I can't get it to work properly, it gives me a NullPointerException whenever I try to run it...
Do you know what's wrong??
Thank you!