2015年9月10日星期四

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?Show More Hint
  2. Two variables is all you need. Try with x and y.Show More Hint
  3. Beware of empty rows. It could be the first few rows.Show More Hint
  4. To write correct code, think about the invariant to maintain. What is it?Show More Hint
  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?Show More Hint
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?Show More Hint
  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.

public class Vector2D {
 
    int i = 0;
    int j = -1;
 
    List<List<Integer>> data;

    public Vector2D(List<List<Integer>> vec2d) {
        data = vec2d;
        int i = 0;
        int j = 0;
    }

    public int next() {
        j++;
        while (i < data.size() && j >= data.get(i).size()) {
            j = 0;
            i++;
        }
        return data.get(i).get(j);
    }

    public boolean hasNext() {
        int tmpJ = j;
        int tmpI = i;
        tmpJ++;
        while (tmpI < data.size() && tmpJ >= data.get(tmpI).size()) {
            tmpJ = 0;
            tmpI++;
        }
        return tmpI != data.size();
    }
}

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

=========

public class Vector2D {
   
    Iterator<List<Integer>> iterator1;
    Iterator<Integer> iterator2;

    public Vector2D(List<List<Integer>> vec2d) {
        iterator1 = vec2d.iterator();
        iterator2 = null;
    }

    public int next() {
        while (iterator2 == null || !iterator2.hasNext()) {
            iterator2 = iterator1.next().iterator();
        }
        return iterator2.next();
    }

    public boolean hasNext() {
        while (iterator2 == null || !iterator2.hasNext()) {
            if (iterator1.hasNext()) {
                iterator2 = iterator1.next().iterator();
            } else {
                break;
            }
        }
        return iterator2 != null && iterator2.hasNext();
    }
}

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

没有评论:

发表评论