Monday, November 23, 2015

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:
  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. 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?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
Solution:
public class Vector2D {
    List flat;
    int index;
    
    public Vector2D(List> vec2d) {
        index = 0;
        flat = new ArrayList();
        for (int i = 0; i < vec2d.size(); i++) {
            for (int j = 0; j < vec2d.get(i).size(); j++) {
                flat.add(vec2d.get(i).get(j));
            }
        }
    }

    public int next() {
        int val = flat.get(index);
        index++;
        return val;
    }

    public boolean hasNext() {
        return index < flat.size();
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */
Follow Up: using only iterators in C++ or iterators in Java
Referencehttp://buttercola.blogspot.com/2015/08/leetcode-flatten-2d-vector.html
Inner iterator must be initilized as Collections.emptyIterator() because the method hasNext() first checks if the innerIterator.hasNext(), so the inner iterator itself must be an iterator at first. 
public class Vector2D {
    Iterator> outer;
    Iterator inner;
    
    public Vector2D(List> vec2d) {
        outer = vec2d.iterator();
        inner = Collections.emptyIterator();  // if outer == null, inner = outer.iterator() will throw exception
    }

    public int next() {
        return inner.next();
    }

    public boolean hasNext() {
        if (inner.hasNext()) {
            return true;
        }
        
        if (!outer.hasNext()) {
            return false;
        }
        
        inner = outer.next().iterator();
        while (!inner.hasNext() && outer.hasNext()) {
            inner = outer.next().iterator();
        }
        return inner.hasNext();
    }
}

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i = new Vector2D(vec2d);
 * while (i.hasNext()) v[f()] = i.next();
 */

No comments:

Post a Comment