Flatten 2D vector

/**
Flatten 2D Vector
Implement an iterator to flatten a 2d vector.
For example, Given 2d vector =
[
  [1,2],
  [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 do you need to keep track?
Two variables is all you need. Try with x and y.
Beware of empty rows. It could be the first few rows.
To write correct code, think about the invariant to maintain. What is it?
The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
Not sure? Think about how you would implement hasNext(). Which is more complex?
Common logic in two different places should be refactored into a common method.
*/


/**
Solution:
-keep track of two variables - one for the current list and one for the current elemetn in the current list
-hasNext() will check if the current list is within alllists.size() and if the current element is within the current list size
-next() will return the current element from teh current list

O(n)
*/
public class Flatten2DVector{
List<List<Integer>> lists;
int curList, curItem;

public Flatten2DVector(List<List<Integer>> vecs){
lists = vecs;
curList = 0;
curItem = 0;
}

boolean hasNext(){
while(curList<lists.size()){
if(curItem<lists.get(curList).size()){
return true;
}
curList++;
curItem = 0;
}
return false;
}

int next(){
if(!hasNext()){
return -1; //no value found, can send error
}
int val = lists.get(curList).get(curItem);
curItem++;
return val;
}

}

No comments:

Post a Comment