Created
April 12, 2013 16:26
-
-
Save dfilimon/5373271 to your computer and use it in GitHub Desktop.
Vector iteration Mahout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} | |
} |
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
This outputs:
0 0 1.000000
1 2 2.000000
2 2 2.000000
3 4 3.000000
4 4 3.000000
5 6 4.000000
6 6 4.000000
Which is unexpected. There should have been (in my mind) two 0 entries.