Implement a iterator to flatten a 2d vector.
For example,
Given 2d vector =
[ [up], [3], [4,5,6]]
By calling next repeatedly until hasnext returns FALSE, the order of elements returned by next should be: [1,2,3,4,5,6]
.
Hint:
- How many variables does you need to keep track?
- Variables are all need. Try with
x
and y
.
- Beware of empty rows. It could be the first few rows.
- To write correct code, think on the invariant to maintain. What is it?
- The invariant is
x
and y
must all-point-a valid point in the 2d vector. Should maintain your invariant ahead of time or right when do you need it?
- Not sure? Think about what you would implement
hasNext()
. Which is more complex?
- Common logic in the different places should is refactored into a Common method.
Public classvector2d { Publicilist<ilist<int>> v {Get;Set;} Private intVerticalcount {Get;Set;} Private intIndex {Get;Set;} PublicVector2d (ilist<ilist<int>>vec2d) {v=vec2d; Verticalcount=0; Index=0; } Public BOOLHasnext () {if(Verticalcount >= v.count ())return false; if(Verticalcount = = V.count ()-1&& index >= V[verticalcount]. Count ())return false; if(Index >=V[verticalcount]. Count ()) {Verticalcount++; while(Verticalcount < V.count () && V[verticalcount]. Count () = =0) {Verticalcount++; } if(Verticalcount = = V.count ())return false; Else{Index=0; return true; } } return true; } Public intNext () {returnv[verticalcount][index++]; }}/** * Your vector2d'll be a called like this : * vector2d i = new vector2d (vec2d), * while (I.hasnext ()) v[f ()] = I.next ( ); */
251. Flatten 2D Vector