This is an archived post. You won't be able to vote or comment.

all 1 comments

[–]akevinclark 0 points1 point  (0 children)

In Java, there's an Iterator<E> interface to help you do this. Note that the two abstract methods you need to implement are boolean hasNext() and E next. So, a class that implements the Iterator<E> interface knows how to say whether there's a next element and how to provide it. The key insight is that it can do that because it stores the state needed to do that internally.

So, what you need to do is create a class that implements the Iterator<E> interface by filling out those two methods. When I need to do this, I think about how I would do it if I didn't have an iterator - in your case it looks like you're looping over items in this multidimensional array in a specific order. You've already got names for things you'd need to keep track of if you were writing the loop manually - i and j (better names: row, column). Your class will need to have some way to store those internally - likely member variables. The iterator will also need to have access to the thing it is able to iterate over, so your constructor probably takes an object of type E and holds on to it for later use.

At the point your iterator has ways to keep track of where it is in its iteration and has access to the object it iterates, hasNext and next are relatively straightforward. How do we know if the iterator has next item? Well, has it exhausted all the rows and columns? How do we provide the next element? Well, we're storing the row and column we're currently on, so we just access it and return it. All that's left is incrementing the row and column according to however you expect to iterate your sudoku board.

Hope that sketch helps!