Skip to content

Instantly share code, notes, and snippets.

@dfilimon
Created April 12, 2013 16:26
Show Gist options
  • Save dfilimon/5373271 to your computer and use it in GitHub Desktop.
Save dfilimon/5373271 to your computer and use it in GitHub Desktop.
Vector iteration Mahout.
@Test
public void testVectorIteration() {
Vector vector = new SequentialAccessSparseVector(100);
vector.set(0, 1);
vector.set(2, 2);
vector.set(4, 3);
vector.set(6, 4);
Iterator<Vector.Element> vectorIterator = vector.iterateNonZero();
Vector.Element element = null;
int i = 0;
while (vectorIterator.hasNext()) {
if (i % 2 == 0) {
element = vectorIterator.next();
}
System.out.printf("%d %d %f\n", i, element.index(), element.get());
++i;
}
}
@alexeyline
Copy link

Currently you can't hold on to a copy of Element when iterating, all your references will share same offset. I'd suggest to change SequentialAccessSparseVector.java

  private final class NonDefaultElement implements Element {

    private final int offset;

      private NonDefaultElement(int offset) {
          this.offset = offset;
      }

      @Override
    public double get() {
      return values.getValues()[offset];
    }

    @Override
    public int index() {
      return values.getIndices()[offset];
    }

    @Override
    public void set(double value) {
      invalidateCachedLength();
      values.setValueAt(offset, value);
    }
  }


  private final class NonDefaultIterator extends AbstractIterator<Element> {

    private int offset = -1;

    @Override
    protected Element computeNext() {
      int numMappings = values.getNumMappings();
      if (numMappings <= 0 || offset + 1 >= numMappings) {
        return endOfData();
      }
      offset++;
      return new NonDefaultElement( offset);
    }

  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment